TABLE 11.5 The open Function mode Designations
For all the options a b and/or a + can be tacked onto the end. For example, the r option can be r+,
rb, or rb+. A b tacked onto a mode indicates that the file is binary. Thus, the mode wb indicates that
a binary file is being open to be written to. The + tacked onto a mode indicates two things. One is that
the file pointer will be at the beginning of the file. The other is that the file is open for both reading
and writing/appending.
Did You Know: What Is a File Pointer?
Think of a file pointer as a place keeper. It keeps your current place in the file for you
as your script reads (or writes) data from the file.
In Listing 11.3, a file called May2012TempF.txt is opened. Before it is opened, a few of the os
functions are used to navigate to the file’s location.
LISTING 11.3 Opening the Temperature File
Click here to view code image
>>> import os
>>> os.chdir('/home/pi/data')
>>> os.getcwd()
'/home/pi/data'
>>>
>>> temp_data_file = open('May2012TempF.txt','r')
>>>
Once the file is opened, methods on the file can be done using the variable temp_data_file.
Notice in Listing 11.3 that when the open function was used, both the file’s name and the mode
arguments were passed as strings. You can also use variables as arguments, if desired.
Using File Object Methods
You can act on an opened file by using its variable name. The file’s variable name in Listing 11.3 is
temp_data_file. This variable name, called a file object, has methods associated with it. For
example, once a file is open, you can check various file attributes. Table 11.6 shows a few of file
object methods for checking file attributes.