Objectives
- Open a text file
- Read records from a text file
- Write records to a text file
- Append records to a text file
- Close a text file
- Calculate the size of a text file
# open a text file for writing fout = open("testfile", "w") # write a string fout.write("This is a test file\n") for i in range(1, 11): # convert numbers 1..10 to strings for writing fout.write("{0}\n".format(i)) fout.close() lineNo = 0 # reopen file for reading fin = open("testfile", "r") # read and display first line as string lineIn = fin.readline() lineNo = lineNo + 1 print("{:0>3d}: {}".format(lineNo, lineIn), end="") # read each line of the rest of the file and convert to integers for line in fin: n = int(line) lineNo = lineNo + 1 # display number read in (with file line number) print("{:0>3d}: {:>3d}".format(lineNo, n)) fin.close()