Python 3 – File seek() Method
In Python programming language, the ‘seek()’ method is used to set the file’s current position to the specified position. The seek() method is used to move the position of the file pointer within a file. You can open a file using the open method in Python. Using this method, you will able to read the file pointer and to move it into a new position.
Here is the syntax of the seek() method in Python:
fileObject.seek(offset[, whence])
Parameters:
– ‘offset’ – It is a number which indicates the position where we want to move the file’s pointer.
– ‘whence’ – It is an optional parameter. It determines the position from where the offset is added. By default, the value of this parameter is zero, which means from the beginning of the file.
The different values of whence are:
– 0: It is the default value that means the position will be set at the beginning of the file.
– 1: This means the position will be set relative to the current position.
– 2: This means the position will be set relative to the file’s end.
Here is an example that demonstrates the use of the seek() method in Python.
## Opening the file
file = open("sample.txt", "r")
# using seek method to move pointer
file.seek(5)
print(file.read())
## Closing the file
file.close()
In the above example, suppose we have a file named ‘sample.txt.’ The ‘seek()’ method is used to move the file pointer from the beginning to 5th index within the file. After that, the content of the file is read from the current position of the file pointer.
Another Example:
with open('sample_file.txt') as f:
content = f.readlines()
content = [x.strip() for x in content]
a = content[0]
b = content[1]
a = int(a)
b = int.(b)
f = open('output.txt', 'w')
c = a + b
f.write(str(c))
f.close()
In the above example, a file ‘sample_file.txt’ is opened with the ‘with’ keyword. Using the ‘readlines()’ method, the content of the file is read into a list ‘content’. The first two lines of the file are stored in variable ‘a’ and ‘b’ respectively. The values stored in ‘a’ and ‘b’ are then converted into integers. After that, the sum of ‘a’ and ‘b’ is computed and stored in variable ‘c.’ Finally, the value of variable ‘c’ is written to a new file ‘output.txt.’
Conclusion
The seek() method in Python is useful when you want to move the file’s pointer to a specific position. This method can be used to read or write data from a file. The method takes two parameters, the ‘offset’ and the ‘whence.’ The ‘offset’ indicates the position where we want to move the file’s pointer, while the ‘whence’ determines the position from where the offset is added. By knowing the working principle of ‘seek()’ method, you can easily move your file’s pointer to a specific position within a file.