Account
Categories

seek() Method


Definition:

The seek() method moves the file pointer to a specific character position in a file.

When you use this method, you write the character number as a parameter from where you want to start reading or writing the data.

If you want to read the file, open it in "r" mode, and if you want to write into the file, open it in "w" mode.

Syntax:

file_object.seek(offset)

Example:

file = open("file1.txt", "r")

file.seek(6)

print(file.read())

file.close()

Suppose file1.txt contains:

Hello Python

Note:

Indexing starts from 0, which means the characters in the file are counted from 0 from the left side.

Output:

Exercise

Create a file and use the seek() method to move the file pointer to a specific position.