Now that you know how to open a file, you should learn how to read one. Reading files is the next
item on this hour’s agenda.
Reading a File
To read a file, of course, you must first use the open function to open the file. The mode chosen must
allow the file to be read, which the r mode does. After the file is opened, you can read an entire file
into your Python script in one statement, or you can read the file line by line.
Reading an Entire File
You can read a text file’s entire contents into a variable by using the file object method .read, as
shown in Listing 11.6.
LISTING 11.6 Reading an Entire File into a Variable
Click here to view code image
...
1: >>> temp_data_file = open('/home/pi/data/May2012TempF.txt', 'r')
2: >>>
3: >>> temp_data = temp_data_file.read()
4: >>> type (temp_data)
5: <class 'str'>
6: >>> print (temp_data)
7: 1 79
8: 2 84
9: 3 85
10: ...
11: 29 92
12: 30 81
13: 31 76
14: >>> print(temp_data[0])
15: 1
16: >>> print(temp_data[0:4])
17: 1 79
18: >>>
In Listing 11.6, you can see that the variable temp_data is used to receive the entire file contents
from the .read method on line 3. The data comes in as a string into the temp_data variable, as
shown on lines 4 and 5, using the type function. You can then access the file data now stored in the
variable by using string slicing. This is shown on lines 14 through 17. (You learned about string
slicing in Hour 10, “Working with Strings.”)
Reading a File Line by Line
With Python, you can have a file read line by line. To read a file line by line into a Python script, you
use the .readline method.
By the Way: What Is Considered a Line?
From Python’s point of view, a text file line is a string of characters of any length that
is terminated by the newline escape sequence, \n.