Junior
What do the methods `tell` and `seek` do in Python?
sobes.tech AI
Answer from AI
The tell() method returns the current position of the file pointer in bytes. The seek(offset, origin) method moves the file pointer to a specified offset.
Parameters of the seek() method:
offset: Number of bytes to move.origin: Reference point for the offset. Possible values:- 0 (or
io.SEEK_SET): Beginning of the file (default). - 1 (or
io.SEEK_CUR): Current position of the file pointer. - 2 (or
io.SEEK_END): End of the file.
- 0 (or
Example usage:
# Creating a file for example
with open("example.txt", "w") as f:
f.write("Hello, world!")
# Opening the file for reading
with open("example.txt", "r") as f:
# Current position - start of the file (0)
print(f.tell()) # Outputs 0
# Reading 5 characters
content = f.read(5)
print(content) # Outputs Hello
# Current position after reading (5 bytes)
print(f.tell()) # Outputs 5
# Moving to 3 bytes from the start of the file
f.seek(3, 0)
print(f.tell()) # Outputs 3
# Reading the remaining part
content = f.read()
print(content) # Outputs lo, world!
# Current position - end of the file
print(f.tell()) # Outputs 13
# Moving 5 bytes back from the end of the file
f.seek(-5, 2)
print(f.tell()) # Outputs 8
# Reading
content = f.read()
print(content) # Outputs world!
Important: In text mode ('r', 'w', 'a') seek() and tell() may not work correctly with unencoded data or when using special characters. It is recommended to use binary mode ('rb', 'wb', 'ab') for precise positioning.