Lecture notes for the Introduction to Computer Science I by James Tam Return to the course web page

Example Programs: File Input And Output

Description

Program name

File input: Reads letter grades from an input file and displays them onscreen (needs input file "letters.txt")

grades.py

Getting command line arguments (inputs to the program as the program is run): only works if exactly two command line arguments are given e.g., "python command_line.py first second".

command_line1.py

Getting a variable number of command line arguments.

command_line2.py

File input and output: An extended version of the previous example that writes the mapped grade points to an output file).

grades2.py

Reads a line at-a-time from an input file but this example iterates through each character of the line in a nested loop.

file_list.py

Builds a list of strings from the lines read in from file. Displays the list with each row prefaced with a count from (0, 1, 2...9, A). The last value is for line 11 and is generated by generating the numeric ASCII code for the character 'A'.

file_list2.py

A file modification of the grades example that illustrates how a program can check if a list element contains the newline ("\n") character.

grades3.py

(New example: not in the notes). A program that can handle the case where the input file is not located in the location specified by the user (default is the current folder or directory) by employing exceptions. Unlike the previous examples this program won't crash if the file cannot be found.

file_exception.py