seek

Once a file is opened, the file pointer that is used in file I/O moves from the beginning to the end of the file. It is possible to move the pointer to a specific position and read the data from that position. This is especially useful when we are interested in a specific line of a file. Let's consider the text file write_file.txt from the previous example. The contents of the file include:

    I am excited to learn Python using Raspberry Pi Zero
This is a line appended to the file

Let's try to skip the first line and read only the second line using seek:

if __name__ == "__main__": 
# open text file to read

file = open('write_file.txt', 'r')

# read the second line from the file
file.seek(53)

data = file.read()
print(data)
file.close()

In the preceding example (available for download along with this chapter as seek_in_file.py), the seek function is used to move the pointer to byte 53 that is the end of first line. Then the file's contents are read and stored into the variable. When this code snippet is executed, the output is as follows:

    This is a line appended to the file

Thus, seek enables moving the file pointer to a specific position.

..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset
18.223.106.100