Python Programming for Raspberry Pi, Sams Teach Yourself in 24 Hours

(singke) #1
5: ... temp_data = temp_data_file.readline()
6: ... print (temp_data,end = '')
7: ... temp_data_file.tell()
8: ...
9: 1 79
10: 5
11: 2 84
12: 10
13: 3 85
14: 15
15: ...
16: 29 92
17: 165
18: 30 81
19: 171
20: 31 76
21: 177
22: >>>

So that you can see the process of the file pointer, another .tell method is embedded in Listing
11.8, inside the for loop on line 7. After each line is read and printed out, the file pointer is updated
to the next character to read.


Reading a File Nonsequentially


You can actually use the file pointer from Listing 11.8 to directly access data within the file. This
requires you to know where the data is located, as with string slicing. To do this, you need to use the
.seek and .read methods.


For a text file, the .read method has the following basic syntax:


Click here to view code image


filename_variable.read(number_of_characters)

In Listing 11.9, you can see in line 1 that the .read method is used on temp_data_file to read
in the first four characters of the file. Using the .tell method on line 4, the file pointer is now
pointing at character number 4. The next .read, on line 6, grabs only one character, which is the
newline (\n) escape sequence. This is why the subsequent print command on line 7 prints out two
blank lines (lines 8 and 9).


LISTING 11.9 Reading File Data Using .read


Click here to view code image


1: >>> temp_data = temp_data_file.read(4)
2: >>> print (temp_data)
3: 1 79
4: >>> temp_data_file.tell()
5: 4
6: >>> temp_data = temp_data_file.read(1)
7: >>> print (temp_data)
8:
9:
10: >>> temp_data_file.tell()
11: 5
Free download pdf