Lesson 06
Random Access — tell() and seek() on a File Pointer
Move inside a Python file with tell() and seek(), read a slice with read(n), and jump the pointer back to any character index.
Sequential read() always continues from the pointer. tell() reports that index. seek() moves it so you can read any slice.
Use the playground at the bottom of this page, then take the quiz.
What you will learn
- What the file pointer index means
tell()to read the current indexread(n)to take the nextncharactersseek(index)to jump, including back to0
The idea
When a text file opens in "r", the pointer starts at index 0. Each read moves it forward by the number of characters taken.
| Call | Effect |
|---|---|
handle.tell() |
Returns the current index. It does not move the pointer. |
handle.read(3) |
Returns the next 3 characters and advances the pointer. |
handle.read() |
Returns everything from the pointer to the end. |
handle.seek(7) |
Puts the pointer at index 7. |
handle.seek(0) |
Puts the pointer back at the start. |
Indexes count characters in this text file. If you seek past the end, the next read() is empty. Seeking is also how w+ and a+ let you read after a write: the pointer is at the end until you move it.
The sample text in this lesson is the word PYTHONDATA. It is long enough to slice, and it is not tied to a private data file.
Example
sample = "PYTHONDATA"
with open("marker.txt", "w", encoding="utf-8") as handle:
handle.write(sample)
with open("marker.txt", "r", encoding="utf-8") as handle:
print("start", handle.tell())
print(handle.read(6), "at", handle.tell())
handle.seek(0)
print(handle.read())PYTHON is the first six characters, so after that read tell() reports 6. seek(0) restarts the pointer and the full word comes back. In the playground, try seek(6) and read the remaining DATA.
Key takeaways
-
The pointer starts at 0 in read mode
-
tell()reports the index and does not move -
read(n)returns n characters and advances -
seek(index)jumps, andseek(0)restarts -
Read after a write in
w+ora+by seeking first -
Previous: read() and readlines()
-
Next: Binary Files
Loading playground…
Check your understanding
Random access quiz
tell() returns:
1 / 10