The seek() method in Python is used to change the current position of the file pointer within a file. It is used to move the file pointer to a specified position.
Here is the syntax of the seek() method:
file.seek(offset, whence)
Here, file is the file object that you want to move the file pointer within. offset is the number of bytes to move the file pointer by, and whence is the reference point from which to move the file pointer. The whence parameter is optional and defaults to 0, which means the beginning of the file.
The valid values for the whence parameter are:
- 0 - move the file pointer relative to the beginning of the file
- 1 - move the file pointer relative to the current position
- 2 - move the file pointer relative to the end of the file
Let's see an example to understand this method:
# Opening a file in read mode
file = open("example.txt", "r")
# Moving the file pointer to the beginning of the file
file.seek(0)
# Reading the first 10 characters of the file
content = file.read(10)
# Printing the content
print(content)
# Moving the file pointer 5 bytes ahead
file.seek(5, 1)
# Reading the next 10 characters of the file
content = file.read(10)
# Printing the content
print(content)
# Moving the file pointer to the end of the file
file.seek(0, 2)
# Reading the last 10 characters of the file
content = file.read(10)
# Printing the content
print(content)
In this example, we opened a file named "example.txt" in read mode and then used the seek() method to move the file pointer to different positions within the file. We first moved the file pointer to the beginning of the file using file.seek(0). Then we read the first 10 characters of the file using the read() method.
Next, we moved the file pointer 5 bytes ahead using file.seek(5, 1) and read the next 10 characters of the file. Then we moved the file pointer to the end of the file using file.seek(0, 2) and read the last 10 characters of the file.
Note that the seek() method only works with file objects that are opened in binary mode or with text files that use an encoding that maps each character to a fixed number of bytes.