CIS 111 Text file I/O

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

Text file notes

  • open a file: f = open(filename, mode)
    • mode 'r' = read, start at beginning of file
    • mode 'r+' = read and write, start at beginning of file
    • mode 'w' = write, create new file or truncate existing file
    • mode 'w+' = read and write, create new file or truncate existing file
    • mode 'a' = write, start at end of file
    • mode 'a+' = read and write, create new file or truncate existing file
    • text mode is the default
    • appending 'b' to mode indicates binary
    • text mode input converts \r\n to \n
  • use with to automatically close files with open(filename) as f: data = f.read()
  • call f.close() at the end of processing the file if you do not use with
  • f.write(value) # writes value to file
    • value must be a string in text mode
    • value must be a bytes object in binary mode
  • f.read() # read entire file
    • returns string if text mode
    • returns bytes if binary mode
  • f.read(int)
    • read up to int bytes
    • returns "" on EOF
  • f.readline()
    • reads one line
    • leaves \n at end of string returned
    • returns "" on EOF
  • file objects are iterable for line in f: print(line, end="")
  • two ways of reading all of file object f into a list
    • mylist = list(f) # f is a file object
    • mylist = f.readlines()
  • seek to a position: f.seek(offset, from_what)
    • 0 = BOF
    • 1 = current position
    • 2 = EOF
  • rewind file to beginning: f.seek(0)
  • find current position (for binary files): f.tell()

Example program

# 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()