Python Tutorial Python Advanced Python Resources Python Libraries
Python Java C++ C C# PHP R SQL DS Algo InterviewQ

Python - File seek() Method



The Python file seek() method is used to sets the current file position in a file stream. The method has an optional parameter which is used to specify absolute file positioning (0), relative file positioning (1) and relative to file's end (2).

Syntax

file.seek(offset, whence)

Parameters

offset Required. Specify position to set in the current file stream.
whence Optional. Specify 0, 1 or 2. Defaults is 0 which means absolute file positioning, 1 means relative to the current file positioning and 2 means relative to the file's end.

Return Value

None.

Please note that if the file is opened in appending mode('a' or 'a+'), any seek() operations will be undone at the next write. If the file is only opened for writing in append mode ('a'), this method is essentially a no-op, but it remains useful for files opened in append mode with reading enabled ('a+'). If the file is opened in text mode (without 'b'), only offsets returned by tell() are legal. Use of other offsets causes undefined behavior.

Please note that not all file objects are seekable.

Example: Using seek() method without optional argument

Lets assume that we have a file called test.txt. This file contains following content:

This is a test file.
It contains dummy content.

In the example below, after reading the first line the offset position of the file is reset to the beginning of the file using seek() method.

#read the file 
MyFile = open("test.txt", "r")
#read first line of the file
print(MyFile.readline(), end="")

#sets the offset position to the
#beginning of the file
MyFile.seek(0)

#read the first line again
print(MyFile.readline(), end="")
MyFile.close()

The output of the above code will be:

This is a test file.
This is a test file.

Example: Using seek() method with optional argument

In the example below, the whence argument is set to 1 for relative offset positioning.

#read the file
MyFile = open("test.txt", "rb")
#read first line of the file
print(MyFile.readline())

#sets the offset position by 12 bytes
#in second line
MyFile.seek(12, 1)

#read the second line offset by 8 bytes
print(MyFile.readline())
MyFile.close()

The output of the above code will be:

b'This is a test file.\r\n'
b'dummy content.'

❮ Python File Handling Methods

5