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

(singke) #1
12: >>> temp_data = temp_data_file.read(4)
13: >>> print (temp_data)
14: 2 84
15: >>> temp_data_file.tell()
16: 9
17: >>>

To reposition the file pointer back to the beginning of the file, you need to use the .seek method.
The .seek method has the following basic syntax:


Click here to view code image


filename_variable.seek(position number)

The position number for the start of the file is 0. Listing 11.10 shows an example of using
.seek and .read to read a file nonsequentially.


LISTING 11.10 Repositioning the File Pointer Using .seek


Click here to view code image


1: >>> temp_data_file.seek(0)
2: 0
3: >>> temp_data = temp_data_file.read(4)
4: >>> print (temp_data)
5: 1 79
6: >>> temp_data_file.seek(25)
7: 25
8: >>> temp_data = temp_data_file.read(4)
9: >>> print (temp_data)
10: 6 84
11: >>>

Notice in Listing 11.10 that after the file pointer is position at 0 on line 1, the .read method is set to
read the next four characters in the file. This is very similar to how the .readline method works
in Listing 11.7. However, because only four characters are read in this example, the newline (\n)
does not need to be suppressed in the print function on line 4.


You need to notice one more item to note in Listing 11.10 before you can move on to the Try It
Yourself section. On line 6, the file pointer is positioned at character 25. This allows the next
.read method to read the four characters starting at that position on line 9. Thus, using the .seek
and .read methods allows you to read a file nonsequentially.


Try It Yourself: Open a File and Read It Line by Line
In the following steps, you will create a file outside Python. After it is created, you
will enter the Python interactive shell environment, open the created file, and read it
into Python line by line. In these steps, you will try out another more elegant way to
read through a file. And, hopefully, have a little fun along the way. Here’s what you
do:


  1. If you have not already done so, power up your Raspberry Pi and log in to the
    system.

Free download pdf