Skip to content
Home » tell() & seek() methods

tell() & seek() methods

Here is a clear, simple, and exam-focused explanation of tell() and seek() methods in Python file handling


tell() and seek() Methods in Python

When working with files, Python maintains an internal file pointer (cursor) that indicates the current read/write position in the file.

  • tell() → shows the current position of the file pointer
  • seek() → moves the file pointer to a specific position

These methods help in navigating through the file.


——————————————

1. tell() Method

Purpose:

Returns the current position of the file pointer.

File positions start from 0 (beginning of file).

Syntax

file_object.tell()

✔ Example

f = open("data.txt", "r")
print(f.tell())     # Output: 0 (start of file)
f.read(5)
print(f.tell())     # Output: 5 (after reading 5 characters)
f.close()

📌 After every read/write operation, the file pointer moves forward.


——————————————

2. seek() Method

Purpose:

Moves the file pointer to a specified position.

Syntax

file_object.seek(offset, from_where)

Parameters

  1. offset → number of bytes to move
  2. from_where (optional):
    • 0 → from beginning of file (default)
    • 1 → from current position
    • 2 → from end of file

Examples of seek()

✔ Example 1: Move to beginning of file

f = open("data.txt", "r")
f.seek(0)    # moves cursor to start

✔ Example 2: Move to 10th character

f = open("data.txt", "r")
f.seek(10)
print(f.read())   # reads from 10th character onward

✔ Example 3: Move forward from current position

f = open("data.txt", "r")
f.seek(5)           # move to 5th character
print(f.read(5))    # read next 5 characters
f.seek(2, 1)        # move 2 characters ahead from current position
print(f.read(5))

✔ Example 4: Move to end of file

f = open("data.txt", "rb")   # must use binary mode for 'from end'
f.seek(0, 2)   # move to end of file
print(f.tell())  # position at end

⚠ In text mode, only seek(offset, 0) and seek(offset, 2) (with offset=0) are reliable.
Binary mode allows full use of seek().


——————————————

Using tell() + seek() Together

f = open("sample.txt", "r")
print("Start:", f.tell())

f.read(7)
print("After reading:", f.tell())

f.seek(0)
print("Back to start:", f.tell())

——————————————

Importance of tell() and seek()

✔ Allows random access to file
✔ Helps in re-reading data
✔ Useful for large files
✔ Allows skipping unnecessary data
✔ Essential for binary file processing


——————————————

Exam-Ready Short Answer

tell() returns the current position of the file pointer in a file.
seek(offset, from_where) moves the file pointer to a specified position.
offset defines how many bytes to move, and from_where (0, 1, 2) specifies whether to move from the beginning, current position, or end of file. These methods are used for random file access and pointer control.