In Listing 11.7, the .readline method is used on the temperature file,
/home/pi/data/May2012TempF.txt. A for loop is used to iterate through the file, line by
line, printing out each read file line.
LISTING 11.7 Reading a File Line by Line
Click here to view code image
>>> temp_data_file = open('/home/pi/data/May2012TempF.txt', 'r')
>>>
>>> for the_date in range (1, 31 + 1):
... temp_data = temp_data_file.readline()
... print (temp_data,end = '')
...
1 79
2 84
3 85
...
29 92
30 81
31 76
>>>
Notice in Listing 11.7 that when printing out the temperature data, the print functions newline (\n)
has to be suppressed by using end=''. This is needed because the data already has a \n character
on the end of each line. If you do not suppress the print function’s newline (\n), your output will
be double spaced.
Did You Know: Stripping Off the Newline!
There may be times when you need to remove the newline characters that are read into
your Python script by the .readline method. You can achieve this by using the
strip method. Since the newline character is on the right side of the line string, you
more specifically use the .rstrip method. If this method were used in Listing 11.7,
it would look like this: temp_data = temp_data.rstrip('\n').
Reading a file line by line, as you would expect, reads the file in sequential order. Python maintains a
file pointer that keeps track of its current position in a file. You can see this file pointer getting
updated after each line read by using the .tell method. In Listing 11.8, the .tell method is
performed right after the file is opened on line 2. You can see that the file pointer is set to 0 , or the
beginning of the file.
LISTING 11.8 Following the File Pointer Using .tell
Click here to view code image
1: >>> temp_data_file = open('/home/pi/data/May2012TempF.txt', 'r')
2: >>> temp_data_file.tell()
3: 0
4: >>> for the_date in range (1, 31 + 1):