Next / Previous / Contents / TCC Help System / NM Tech homepage

9. Input and output

Python makes it easy to read and write files. To work with a file, you must first open it using the built-in open() function. If you are going to read the file, use the form “open(filename)”, which returns a file object. Once you have a file object, you can use a variety of methods to perform operations on the file.

9.1. Reading files

For example, for a file object F, the method F.readline() attempts to read and return the next line from that file. If there are no lines remaining, it returns an empty string.

Let's start with a small text file named trees containing just three lines:

yew
oak
alligator juniper

Suppose this file lives in your current directory. Here is how you might read it one line at a time:

>>> treeFile = open ( 'trees' )
>>> treeFile.readline()
'yew\n'
>>> treeFile.readline()
'oak\n'
>>> treeFile.readline()
'alligator juniper\n'
>>> treeFile.readline()
''

Note that the newline characters ('\n') are included in the return value. You can use the string .rstrip() method to remove trailing newlines, but beware: it also removes any other trailing whitespace.

>>> 'alligator juniper\n'.rstrip()
'alligator juniper'
>>> 'eat all my trailing spaces         \n'.rstrip()
'eat all my trailing spaces'

Use the .close() method once you are done processing the file. Once you have closed a file, you can't perform any operations on it.

>>> treeFile.close()
>>> treeFile.readline()
Traceback (most recent call last):
  File "<stdin>", line 1, in ?
ValueError: I/O operation on closed file

To read all the lines in a file at once, use the .readlines() method. This returns a list whose elements are strings, one per line.

>>> treeFile=open("trees")
>>> treeFile.readlines()
['yew\n', 'oak\n', 'alligator juniper\n']
>>> treeFile.close()

A more general method for reading files is the .read() method. Used without any arguments, it reads the entire file and returns it to you as one string.

>>> treeFile = open ("trees")
>>> treeFile.read()
'yew\noak\nalligator juniper\n'
>>> treeFile.close()

To read exactly N characters from a file F, use the method F.read(N). If N characters remain in the file, you will get them back as an N-character string. If fewer than N characters remain, you will get the remaining characters in the file (if any).

>>> treeFile = open ( "trees" )
>>> treeFile.read(1)
'y'
>>> treeFile.read(5)
'ew\noa'
>>> treeFile.read(50)
'k\nalligator juniper\n'
>>> treeFile.read(80)
''
>>> treeFile.close()