User Guide
Table Of Contents
151
Python makes a distinction between working with a text file and
working with a binary file. The key difference between the two is
that with text files Python deals with the text encoding and line
break formats for you. In binary mode, you have access to each
byte that makes up the file, and it is up to you to decide how to
process them.
When reading and writing to a text file, you can only use string
objects. When reading and writing to a binary file, use bytes and
bytearray objects.
Reading from a Text File
To read from a file, open it using the mode “r”, or any of the
other modes that support reading. Then use the method read()
to read a number of characters from the file.
You must remember to close files once you are finished working
with them. Do this with the close() method. If you do not close a
file then you might be unable to work with the file again, until
you restart the Pi.
For example, to read the “message of the day” (MOTD) file:
motd = open("/etc/motd", "r")
message = motd.read()
print(message)
motd.close()
If you do not specify how many characters to read, read() will
fetch the entire contents of the file. To read only ten characters:
motd.read(10)
a Open a file for “appending”. Anything you write is
added to the end. This overwrites the existing file
or, if it does not exist, creates the file.
ab Open a file for appending binary data.
Mode Description