12. File I/O

12.1 Open

  • Files are opened using the open() function.

def main():
    f = open('lines.txt')
    for line in f:
        print(line.rstrip())
  • The open function returns a file object. This object is an iterator, so a for loop can be used to get it one line at a time without having to buffer the entire file in memory.

  • rstrip strips any white space and line endings.

  • By default, it’s in read-only mode. Same as f = open('lines.txt'. 'r').

  • For write mode, f = open('lines.txt', 'w').

  • For read and write, f = open('lines.txt'. 'r+')

12.2 Newline

  • specified using \n.

12.3 Write text

  • To write, use print and write to file

def main():
    infile = open('lines.txt', 'rt')
    outfile = open('lines-copy.txt', 'wt')
    for line in infile:
        print(line.rstrip(), file=outfile)
        print('.', end='', flush=True)
    outfile.close()
    print('\ndone.')
  • rt opens in read and text mode (which is also the default).

  • Good idea to close the outfile explicitly

  • An alternative to print is to use outfile.writelines(line).

12.4 Write binary

def main():
    infile = open('berlin.jpg', 'rb')
    outfile = open('berlin-copy.jpg', 'wb')
    while True:
        buf = infile.read(10240)
        if buf:
            outfile.write(buf)
            print('.', end='', flush=True)
        else: 
            break
    outfile.close()
    print('\ndone.')
  • rb opens in read and binary mode.

  • This file (image) can’t be opened in text mode.