seek() and tell() methods in Python
The seek and tell methods in Python are used for manipulating the current position of the file pointer in a file.seek() method
The seek method allows you to move the file pointer to a specific position in the file. You can use it to reposition the file pointer to a specific location, so that subsequent reads or writes will start from that position. Syntax:
file.seek(offset, from_where)
The seek method takes two arguments: the first is the offset from the beginning of the file, and the second is an optional reference point that specifies where the offset is relative to. By default, the reference point is the beginning of the file. The offset can be positive (to move the pointer forward) or negative (to move the pointer backward).
with open("file.txt", "r") as f:
print(f.read(5)) # Prints the first 5 characters of the file
f.seek(5) # Move the file pointer to the 6th character
print(f.read(5)) # Prints the next 5 characters of the file

tell() method
The tell method returns the current position of the file pointer, in bytes from the start of the file. The position is an integer that represents the number of bytes from the beginning of the file. Syntax:
file.tell()
You can use it to determine the current position of the file pointer, for example, to keep track of how much of a file has been processed.
with open("file.txt", "r") as f:
print(f.read(5)) # Prints the first 5 characters of the file
print("Current position:", f.tell()) # Prints the current position of the file pointer
f.seek(5) # Move the file pointer to the 6th character
print(f.read(5)) # Prints the next 5 characters of the file
Note that when you open a file in text mode, the tell method returns the number of characters, not the number of bytes. In binary mode, the tell method returns the number of bytes.
Related Topics
- How to open and close a file in Python
- How to write files in python
- How to read a file properly in Python
- How to read a file line by line in Python
- How to use Split in Python
- Directory Operations Using Python
- How to check that a file or directory exists with Python
- File Access Mode in Python
- Difference between read, readline and readlines | python
- How to Copy a File using Python