Python - File seek() Method


Advertisements

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.

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

In the below example, the seek() method is used to set the offset position of the file called MyFile. As the default value of the whence argument is 0 hence it sets the offset position relative to absolute which is 1 in this case.

MyFile = open("python_test.txt", "r")
#sets the offset position to 1(absolute positioning)
MyFile.seek(1)
print(MyFile.readline())

#sets the offset position to 1(absolute positioning)
MyFile.seek(1)
print(MyFile.readline())

Output

ython is a programming language.

ython is a programming language.

Example: Using seek() method with optional argument

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

MyFile = open("python_test.txt", "r")
print(MyFile.readline(7))

#sets the offset position to 7(relative positioning)
MyFile.seek(0, 1)
print(MyFile.readline())

Output

Python 
is a programming language.

Python File Handling Methods
Advertisements