file-seek-method-python

A file in a computer system is a container for storing information like texts that are alike to paper documents. Likewise, Python supports the file feature where we can read data, append data, and write new data into it.

Python file object have different methods like close(), fileno(), flush(), isatty(), readlines(), seek(), seekable(), etc. Each of them has different functionality. Right now we will discuss seek() method here in this blog with a couple of examples.

 

Python file seek() method sets the file’s current position at the desired offset. This method holds two arguments offset and whence.

offset
Here offset is the required argument that denotes either to move left or right of the file. Positive offset refers to setting file position to the right of the file whereas negative offset refers to the left of the file with respect to the reference point given by the whence argument.

whence
It is the optional argument by default set to 0 or SEEK_SET.
Possible values for the whence:

SEEK_SET or 0 - This is the default value that seeks from the beginning of the file. Here the offset should be zero or positive.
SEEK_CUR or 1 - This value denotes the current file position. The offset can be either positive or negative.
SEEK_END or 2 - This value indicates the pointer is at the end of the file. Here the offset is usually negative.

If you are confused with SEEK_SET, SEEK_CUR, and SEEK_END it’s nothing but just the constant or global value set by the Python os() module as:

>>> import os
>>> os.SEEK_SET
0
>>> os.SEEK_CUR
1
>>> os.SEEK_END
2

 

Syntax

seek(offset, whence=SEEK_SET)

We apply seek() method operations on the text file called about_python.txt that is located in the working directory. Below is the snapshot of that text file.
about-python

Example 1:

Read from the second line of a file

with open(r'about_python.txt', 'r') as f:
    first_line_length = len(f.readline())  # find length of first line
    # move file position to the second line
    f.seek(first_line_length)
    print(f.read())

Output:

Python is high-level programming language.
Python is widely using in Data Science project.
Python is dynamically typed language.

Above, we open the file in normal read mode. Then we calculate the length of the first line by using two functions readline() and len().

readline() just read the first line from the file, also if we call the same function a second time, then the second line will be called from the file. Then we calculate the length of the first line by using len() function so that we move that character’s length ahead from the beginning of the file.

 

Example 2:

Read from 5 characters right from a second-line position.

with open(r'about_python.txt', 'r') as f:
    first_line_length = len(f.readline())

    f.seek(first_line_length) # move file pointer to 2nd line

    # move right to 5 characters from current position
    f.seek(5, 1)

    print(f.read())

Output:

---------------------------------------------------------------------------
UnsupportedOperation                      Traceback (most recent call last)
<ipython-input-32-60603d15fcb2> in <module>
      5 
      6     # move right to 5 characters from current position
----> 7     f.seek(5, 1)
      8 
      9     print(f.read())

UnsupportedOperation: can't do nonzero cur-relative seeks

Here in the above program, we got UnsupportedOperation as an exception. This is because we opened the file in normal read mode which doesn’t support the offsetting from the current position that the second line. This mode only supports seeking relative to the beginning of the file.

So in this case we have to open the file in binary mode so that the file position can be moved forward or backward based on the current position as:

with open(r'about_python.txt', 'rb') as f:
    first_line_length = len(f.readline())

    f.seek(first_line_length) # move file pointer to 2nd line

    # move right to 5 characters from current position
    f.seek(5, 1)

    print(f.read().decode('utf-8'))

Output:

n is high-level programming language.
Python is widely using in Data Science project.
Python is dynamically typed language.Flask, Django and FastAPI are the web frameworks for Python.

In the above output, offsetting 5 characters ahead from the current position skip the letters “Pytho” and print the rest.

 

Example 3:

Write at the end of the file

with open('about_python.txt', 'r+') as f:
    # move file position to the end of file
    f.seek(0, 2)

    # insert new line with write method
    f.write("\nFlask, Django and FastAPI are the web frameworks for Python.")

    # move pointer back to the beginning
    f.seek(0)

    print(f.read())

Output:

Python is the most popular language.
Python is high-level programming language.
Python is widely using in Data Science project.
Python is dynamically typed language.
Flask, Django and FastAPI are the web frameworks for Python.

First, we moved the file position to the end of the file using value 2 as a second argument. Then we add a new line to the current file position.

After reading the file from the beginning, we set the pointer back to the initial position using seek(0) method and read the updated file using the read() method.

 

Reference: Python Docs

Leave a Reply

Your email address will not be published.