Python Binary file seek
Seek to a byte offset before reading a fixed-width record.
A simple example
Binary file seek
- Start with Three bytes, 4, 7, 9
- Do this Read at byte offset 1
- Result 7
Syntax
stream.seek(2)
Run these examples in Python
Save one example at a time as lesson.py. Use Python 3.9 or later.
python3 lesson.pyRead the third locker status
A parcel desk stores one byte for each locker. Because the records have fixed width, the operator can read the third locker directly without first processing the other two statuses.
from pathlib import Path
from tempfile import TemporaryDirectory
with TemporaryDirectory() as folder:
base = Path(folder)
board = base / "board"
board.write_bytes(bytes([6, 8, 9]))
with board.open("rb") as stream:
stream.seek(2)
print(stream.read(1)[0])
9
The third locker occupies offset two and stores the value nine.
Read a display preset
A museum sign saves three brightness levels as individual bytes. Read the unsigned byte at the indicated zero-based offset. Which stored sample is returned?
Read the first locker state
A desk stores two status values in a compact file. Read the unsigned byte at the indicated zero-based offset. Which stored sample is returned?
What to watch for
Offsets refer to bytes. Variable-length text needs a different indexing strategy.