tell() and seek()

M3-R5.1 · Chapter 7: File Processing · 3 min read

File Position Functions — tell() and seek()

Python maintains an internal file pointer that tracks the current read/write position within a file. tell() and seek() allow you to work with this pointer.

1. tell() Function

tell() returns the current position of the file pointer as an integer (number of bytes from the beginning of the file).

f = open('sample.txt', 'r')

 

print(f.tell())     # Output: 0  (at beginning)

 

f.read(5)           # Read 5 characters

print(f.tell())     # Output: 5  (moved 5 bytes forward)

 

f.read(10)          # Read 10 more characters

print(f.tell())     # Output: 15

 

f.close()

2. Seek() Function

seek(offset, whence=0) moves the file pointer to a specific position.

Parameter

Value

Meaning

Offset Relative To

whence

0 (default)

Seek from beginning of file

Start of file

whence

1

Seek from current position

Current pointer position

whence

2

Seek from end of file

End of file

offset

Positive int

Move forward that many bytes

(depends on whence)

offset

0

Go to the reference point

(depends on whence)

offset

Negative int

Move backward (only with whence=2)

(only for binary files)

f = open('sample.txt', 'r')

 

f.read(10)              # Read first 10 characters

print(f.tell())         # Output: 10

 

f.seek(0)               # Go back to beginning

print(f.tell())         # Output: 0

 

f.seek(5)               # Move to position 5 from start

print(f.read(3))        # Read 3 chars starting at position 5

 

f.seek(0, 2)            # Go to end of file

print(f.tell())         # Output: total size of file in bytes

 

f.close()

▸  Practical Example: Using tell() and seek() Together

f = open('data.txt', 'r')

 

# Save current position

pos = f.tell()

print('Position before read:', pos)    # 0

 

# Read some data

data = f.read(20)

print('Data read:', data)

print('Position after read:', f.tell()) # 20

 

# Return to saved position

f.seek(pos)

print('After seek back:', f.tell())     # 0

 

f.close()