This guide explains seek and tell: random access in files through a focused Python example. You will learn the behavior to expect, why it matters in a real program, and how to recognize the common mistakes before applying it in your own project.
What You Will Learn
seek(offset, whence) moves a file cursor and tell() reports its current position. This enables controlled random access, especially in binary files.
When and Why to Use It
The following example focuses on a practical use of Seek and Tell: Random Access in Files.
Step-by-Step Example
from io import BytesIO
binary_stream = BytesIO(b"ABCDEFG")
print(binary_stream.read(2))
print(binary_stream.tell())
binary_stream.seek(4)
print(binary_stream.read(2))
Understanding the Example
Reading two bytes moves the cursor to position 2. Seeking to byte position 4 makes the next read return EF.
Expected Output
b'AB'
2
b'EF'
Important Behavior and Edge Cases
In text streams, seek offsets are not generally arbitrary character indexes because encoded characters can occupy several bytes.
Try It Yourself
Read bytes 3 through 5 from an in-memory binary stream.
For file examples, use a dedicated practice directory or a temporary directory. Make sure you understand whether a call reads, creates, overwrites or appends before using it on important files.
Common Beginner Mistakes
- In text streams, seek offsets are not generally arbitrary character indexes because encoded characters can occupy several bytes.
- Assuming the current working directory, encoding, filesystem contents or file permissions will be identical on every computer.
- Skipping the practice step and assuming the example covers every input. Test at least one normal case and one edge case relevant to this topic.
Key Takeaways
- seek(offset, whence) moves a file cursor and tell() reports its current position.
- Reading two bytes moves the cursor to position 2.
- Apply the technique deliberately, checking its documented input requirements and failure behavior before integrating it into a larger project.