Python Binary Files Explained: Bytes, Pickle and a Worked Record Trace

Trace five raw bytes, then follow three pickled student records through loading, filtering, searching and a safe marks update.

KnowledgeGate Team

Exam prep & CS education

Updated 5 Dec 20266 min read
Python Binary Files Explained: Bytes, Pickle and a Worked Record Trace

A .dat extension does not explain what a file contains. In binary mode, read() produces bytes rather than decoded text, while a pickled Python record is not meant to be decoded line by line. A five-byte payload 4B 47 00 FF 0A spans offsets 0 to 4; three student records are written, filtered, searched and safely updated. The modes rb, wb and ab have different effects, and binary-file questions turn them into pointer, object-count and truncation traps.

A binary file stores bytes, while a format gives those bytes meaning

A binary file is a sequence of bytes. In text mode, an encoding translates characters to or from bytes, and Python may also handle line endings. In binary mode, Python performs no decoding and returns bytes, as specified in the official Python open() documentation.

The byte value 65 does not have one universal meaning. It can represent ASCII A, one colour channel in an image, part of an integer, or part of a serialised object. The format decides how a program should interpret it. An extension such as .dat is only a naming convention, not a parser.

Keep three layers separate: raw bytes such as bytes([75, 71, 0, 255, 10]), a serialisation format such as pickle, and an application record such as {"roll": 101, "name": "Asha", "marks": 72}. File I/O belongs among the practical Python foundations covered under Coding & Skills. The published File Handling in Python: Read, Write, Append, CSV and Binary Examples explains the general path, mode, stream and cursor model, while the binary/pickle treatment here focuses on raw bytes, pickle streams and variable-length record rewrites.

Trace five raw bytes through write, read, seek and tell

Start with this exact program:

python
payload = bytes([75, 71, 0, 255, 10])

with open("sample.bin", "wb") as file:
    written = file.write(payload)
    end_position = file.tell()

with open("sample.bin", "rb") as file:
    first_two = file.read(2)
    after_read = file.tell()
    file.seek(2)
    middle_two = file.read(2)

The file has five positions: 0:75 (0x4B, K), 1:71 (0x47, G), 2:0 (0x00), 3:255 (0xFF) and 4:10 (0x0A). Therefore, write() returns 5, and tell() immediately after the write returns 5.

When the file is reopened, the pointer starts at offset 0. Reading two bytes produces b'KG' and moves the pointer to 2, so after_read == 2. The absolute call seek(2) leaves it at offset 2. Reading the next two bytes produces b'\x00\xff' and moves it to 4.

Mode wb creates a file or truncates an existing one before writing. Mode rb reads without changing the file. If these pointer operations feel too compressed, use the Python Tutorial: 13-Step Self-Study Path to DSA to revise data types and functions first.

Five-byte binary file diagram showing offsets 0-4, byte values, and read-pointer movement.

Pickle turns Python objects into a binary data stream

The pickle documentation defines pickle.dump(object, binary_file) as serialising an object to a binary file and pickle.load(binary_file) as reconstructing the next object from that stream. Pickle is Python-specific object serialisation. It is not a human-readable table format, and it is not a general name for every binary file.

Write these three dictionaries in order:

python
import pickle

students = [
    {"roll": 101, "name": "Asha", "marks": 72},
    {"roll": 102, "name": "Bharat", "marks": 64},
    {"roll": 103, "name": "Charu", "marks": 81},
]

with open("students.dat", "wb") as file:
    for student in students:
        pickle.dump(student, file)

The loop makes one stream containing three consecutive pickled objects. Their logical order is fixed by the calls, but their exact byte lengths and offsets are not assumptions the program should make. Pickle protocol and implementation details can affect the representation.

Fully worked record trace: load, filter, search and update

Read the objects until the stream is exhausted:

python
loaded = []
with open("students.dat", "rb") as file:
    while True:
        try:
            loaded.append(pickle.load(file))
        except EOFError:
            break

The three successful loads return rolls 101, 102 and 103, in that order. EOFError ends the loop after the third object. It is not a fourth record.

Now filter with student["marks"] >= 70. Asha qualifies with 72, Bharat is rejected with 64, and Charu qualifies with 81. The result count is 2. Its total is 72 + 81 = 153, so the average is 153 / 2 = 76.5.

A search for roll 102 returns Bharat with marks 64. A search for roll 999 examines all three records and returns no match. Suppose Bharat's marks must change from 64 to 74. Update the dictionary in loaded, then rewrite the complete collection:

python
for student in loaded:
    if student["roll"] == 102:
        student["marks"] = 74
        break

with open("students.dat", "wb") as file:
    for student in loaded:
        pickle.dump(student, file)

The rewrite is deliberate. Pickled objects can have variable lengths, so overwriting an assumed byte range is unsafe. Reopening with wb truncates the old stream, after which all three validated records are dumped again in order.

The rewritten records are (101, Asha, 72), (102, Bharat, 74) and (103, Charu, 81). Their total is 72 + 74 + 81 = 227. The mean is 227 / 3 = 75.666..., which rounds to 75.67 at two decimal places. All three now satisfy marks >= 70.

Pickle stream diagram showing three student records, filtering, search and a full-stream rewrite with updated marks.

Modes, trust and rewrite traps that break correct-looking code

Each common mistake has a direct correction:

  • Wrong move: Open a pickle file with w or r. Consequence: Those modes use text I/O. Correction: Use wb for writing and rb for reading.

  • Wrong move: Open an existing file with wb before preserving its records. Consequence: The old content is truncated. Correction: Use wb only when creating or deliberately rewriting the complete stream.

  • Wrong move: Treat ab as an editing mode. Consequence: It can append new objects but cannot edit old ones in place, and an append-only handle cannot be used by load(). Correction: Reopen with rb to read, modify a validated collection, then rewrite it.

  • Wrong move: Use for range(3) when the record count is unknown. Consequence: The loop may stop early or attempt too many loads. Correction: Read until EOFError.

  • Wrong move: Assume one dump always means one dictionary. Consequence: pickle.dump(students, file) stores one list object, while the loop above stores three dictionary objects. Correction: Match the load logic to the dump structure.

There is also a trust boundary. The official pickle documentation warns that pickle is not secure. Unpickle only data from trusted sources. For unknown or exchanged data, choose a safer validated interchange format suited to the task.

How binary-file questions test the same model

Binary-file questions usually test a small set of reasoning patterns: choose the correct mode, predict the type returned by read(), trace the pointer after read(), seek() and tell(), count dump or load calls, filter records, detect truncation, and distinguish end-of-file from a stored value.

Check the model with three exact results:

  1. For the five-byte file, seek(1); read(3) starts at byte 71 and returns b'G\x00\xff'. Three bytes are consumed, so the final position is 1 + 3 = 4.

  2. One call to pickle.dump(students, file) writes one list object. One matching pickle.load(file) returns that list with length 3. The earlier loop instead makes three dump calls, so it permits three successful loads.

  3. After Bharat's update, marks > 75 keeps only Charu with 81. The condition marks >= 70 keeps Asha, Bharat and Charu.

The Binary Files subtopic has more than 15 practice questions.Python Output-Based Questions: 13 Solved Snippets.

Short version and the next study step

Binary mode moves bytes, while the format supplies their meaning. Pickle serialises Python objects, each dump() must match the intended loading structure, and changing variable-length records should trigger a complete validated rewrite. Here, the raw payload occupies five byte positions, while the updated student total is 227 and its average is 75.67. Use Python Programming for file handling and core-language revision. Once Python I/O, collections and functions feel comfortable, continue with DSA Using Python.