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(”, which returns a
file object. Once you have a file
object, you can use a variety of methods to perform
operations on the file.
For example, for a file object
, the method
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 (
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
>>> 'alligator juniper\n'.rstrip() 'alligator juniper' >>> 'eat all my trailing spaces \n'.rstrip() 'eat all my trailing spaces'
.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
>>> treeFile = open ("trees") >>> treeFile.read() 'yew\noak\nalligator juniper\n' >>> treeFile.close()
To read exactly
characters from a file
, use the method
characters remain in the file,
you will get them back as an
-character string. If fewer than
remain, you will get the remaining characters in the file
>>> treeFile = open ( "trees" ) >>> treeFile.read(1) 'y' >>> treeFile.read(5) 'ew\noa' >>> treeFile.read(50) 'k\nalligator juniper\n' >>> treeFile.read(80) '' >>> treeFile.close()