Python seek method:

The seek method of IOBase class sets the stream position to the given byte offset. The offset is interpreted relative to the position indicated by whence. In other words, the seek() method changes the position of the file handle to the specified position.

Method Signature

The signature for the seek method is as shown below.

fileObject.seek(offset, whence)

Method parameters and return type

  • Here, the seek() method takes offset and whence as a parameter. The offset is a number of bytes file handle needs to move. Whereas, whence is an optional parameter that indicates the position from where the offset is calculated. It takes one of the three values given below :
    0 – offset calculated from the beginning
    1 – offset calculated from the current position
    2 – offset calculated from the end
  • However, it returns a new absolute position.

Python seek method Examples:

Example 1: In this case, we will open a file in w+ mode and read it after writing.

# Opening a file 
f1 = open("test.txt", "w+")

# Writing 
f1.write("Hello World")
f1.write("\nPython Programming")

# This statement will not read anything as file pointer points to end
print("Reading after write but before seek")
print(f1.read())

#Using seek
f1.seek(0)

#Reading 
print("Reading after seek")
print(f1.read())

# closing
f1.close()

Output

Reading after write but before seek

Reading after seek
Hello World
Python Programming

Example 2: In this case, we will open a file in read mode and set whence to read from the current position.

# Opening a file 
f1 = open("test.txt", "r")

#Using seek
f1.seek(6)
f1.seek(0,1)

#Reading from current cursor position
print("Reading after seek")
print(f1.read())

# closing
f1.close()

Output

Reading after seek
World
Python Programming

Example 3: In this case, we will open a file in w+ mode and use the seek method to overwrite the content of file.

# Opening a file 
f1 = open("test.txt", "w+")
f1.write("Hello World")
f1.write("Welcome to world of Programming")

#Using seek and writing
f1.seek(5)
f1.write("This text will be overwritten")

#Reading 
print("Reading file")
f1.seek(0)
print(f1.read())

# closing
f1.close()

Output

Reading file
HelloThis text will be overwrittengramming

Conclusion

Hence, the seek() method sets the position of filehandle to the desired offset.

References

Happy Learning 🙂

Leave A Comment