Seeking

Seeking is the process of moving a pointer within a file to an arbitrary position. This allows you to get data from anywhere within the file without having to start at the beginning every time.

The seek() method can take several arguments. The first argument (offset) is the starting position of the pointer. The second, optional, argument is the seek direction from where the offset starts. The default value is 0 which indicates an offset relative to the beginning of the file, 1 is relative to the current position within the file, and 2 is relative to the end of the file.

The tell() method returns the current position of the pointer within the file. This can be useful for troubleshooting (to make sure the pointer is actually in the location you think it is) or as a returned value for a function.

One caveat to this is that text files can only be sought relative to the beginning of the file (starting with Python 3.2). Binary files don't suffer from this limitation.

As a best practice, it is advised that, instead of using 0, 1, or 2 for the offset starting position, you should import the os library and use the values os.SEEK_SET, os.SEEK_CUR, and os.SEEK_END. This is because the os library will use whatever values the operating system uses for seeking, rather than hardcoded numbers, just in case the OS does something different. This also ties in to the tell() method, as it can be used to help seek within a text file, as demonstrated in the following screenshot:

File seeking

The os module is imported in line 7 and the file is opened. Line 9 returns the current location of our position within the file; zero indicates the beginning of the file.

In line 10, we move the pointer ahead in the file by four characters. But when we try to move ahead another 12 characters in line 11, we receive an error. The error indicates that Python can't perform relative seeking from the current location; it can only do this from the beginning (zero) position. To fix this, we first confirm our position (line 12), then use tell() and os.SEEK_SET in line 13 to move ahead 12 characters.

Line 14 jumps us to the end of the file, then we move back three characters in line 15.

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

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