Library contents

Python Binary file seek

Seek to a byte offset before reading a fixed-width record.

A simple example

Binary file seek

  1. Start with Three bytes, 4, 7, 9
  2. Do this Read at byte offset 1
  3. Result 7
Offsets start at zero. Moving one byte past the start selects the second byte.

Syntax

Python 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.py

Read 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.

Result9
lesson.py
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])
Output
9

The third locker occupies offset two and stores the value nine.

Advertisements

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?

Given12 · 80 · 200 | offset 2
Worked result200

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?

Given7 · 25 | offset 0
Worked result7

What to watch for

Offsets refer to bytes. Variable-length text needs a different indexing strategy.

Documentation for Binary file seek