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

10. 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.

10.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'

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']

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'

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)
''

One of the easiest ways to read the lines from a file is to use a for statement. Here is an example:

>>> >>> treeFile=open('trees')
>>> for treeLine in treeFile:
...     print treeLine.rstrip()
... 
yew
oak
alligator juniper

As with the .readline() method, when you iterate over the lines of a file in this way, the lines will contain the newline characters. If the above example did not trim these lines with .rstrip(), each line of output would be followed by a blank line, because the print statement adds a newline.