Skip to main content

seek()

The seek() function in Python is a method used in file operations to change the current position of the file read/write pointer within a file. It takes a single argument which specifies the offset with respect to a reference point. The reference point is determined by an optional second argument, and if not provided, it defaults to the beginning of the file. This method is commonly used when you want to move around within a file, either to read from a specific location or to write at a specific location.

Parameter Values

Parameter Description
offset

An integer representing the position in the file to seek to.

whence

An optional integer specifying the reference position for the seek operation. 0 represents the beginning of the file, 1 represents the current file position, and 2 represents the end of the file.

Return Values

The seek() method in Python returns the new file position as an int.

How to Use seek() in Python

Example 1:

The seek() method allows you to change the current file position in a file object. It takes two arguments, offset for the number of bytes to move, and whence for the reference position (0 for the beginning of the file, 1 for the current position, and 2 for the end of the file).

with open('data.txt', 'r') as file:
    file.seek(10, 0)
    print(file.read())