next up previous contents
Next: Methods for Writing Up: File Objects Previous: File Objects   Contents

Methods for Reading

The readline method reads a single line from a file, including its terminating newline. (Under Windows, when Python reads text from a file, it discards the line feed which is on each line, leaving just a newline character.) To eliminate this newline, a common practice is to replace the read line with a string slice which eliminates the last character of the line:

>>> f = open('inputfile','r')
>>> line = f.readline()
>>> line
'Line one\012'
>>> line = line[:-1]
>>> line
'Line one'
Each call to the readline method will read the next line in the file until the contents of the file are exhausted; from that point on, python will return a completely empty string (i.e. no blanks or newlines), until the file is rewound (Section 5.4.4) or closed and reopened. If the goal is to process all of a file, however, you can iterate over each line of the file directly using a for loop (Section 6.5).

The readlines method reads an entire file in a single call and returns a list consisting of all of the lines in the file; each element of the list returned by readlines contains one line (including the terminating newline) from the file. Once the readlines method is invoked once, subsequent calls on the same file object will return an empty list, unless the file is rewound (Section 5.4.4) or closed and reopened.

The read method reads an entire file in a single call and returns the contents of the file in a scalar string variable, with newlines embedded within the string. An optional integer argument n limits the amount of data read to n bytes.

Note that the readlines and read methods both read the entire contents of a file into memory, and may cause problems when reading very large files.


next up previous contents
Next: Methods for Writing Up: File Objects Previous: File Objects   Contents
Phil Spector 2003-11-12