File Positions and Seeking
A seekable stream can move its position before the next read or write. Offset rules depend on the stream type.
- Source
- Anbloq
- Language
- English
- Created
- Updated
- Chapters
- 4
- Reading time
- 1 min
In this article4 chapters
Trace a binary read
From byte offset zero, reading three bytes of a normal file moves the next position to offset three. Seeking to zero then rereading can produce those original bytes if the file was not changed. Binary mode preserves the underlying offsets.
Respect text and stream limitations
Python text positions can be opaque cookies from tell, with restricted seek operations. Pipes may not support seeking at all. A function precondition should name the access pattern a format parser requires.[1]
Follow the byte cursor through reads and repositioning
In binary data ABCDE, reading two bytes returns AB and moves the position to two. Seeking to one and reading two returns BC. Repositioning changes future reads and does not modify existing bytes. See negative indices for a related but distinct in-memory position model.
Initial position 0
read(2) → AB, position 2
seek absolute 1 → position 1
read(2) → BC, position 3
Require a seekable source when the algorithm depends on it
Pipes and some streams do not support arbitrary seeks. Text-mode offsets may also be governed by decoding and newline translation. Keep a separate copy of a header if only forward streaming is available. Test seeking past the range under the specific API.