Skip to lesson content
navan✳THE BUILD LABPYTHON 3
0/101 complete
BUILD LAB / PYTHON/ Files with a future
EXPERIMENT 32 / 101

Bytes do not need quotes.

Read raw bytes and calculate a digest without loading an entire file.

ADVANCED LAB
BY NAVAN SAMI◷ 10 MIN READPYTHON 3

01 The idea

Text is an interpretation of bytes; binary mode gives you the bytes directly. Images, archives, and arbitrary downloads should not be decoded as text. A cryptographic hash summarises the exact byte sequence. Reading fixed-size chunks keeps the working memory bounded, although a digest alone does not establish who produced a file.

02 The experiment

Read it once. Predict what will happen. Then copy it into a .py file and run it in your local Python setup.

binary_files.py
from pathlib import Path
import hashlib
path = Path("payload.bin")
path.write_bytes(b"abc")
digest = hashlib.sha256()
with path.open("rb") as stream:
    while chunk := stream.read(65536):
        digest.update(chunk)
print(digest.hexdigest())
↳ EXPECTED OUTPUT
ba7816bf8f01cfea414140de5dae2223b00361a396177a9cb410ff61f20015ad

03 Under the hood

  1. 1

    rb prevents text decoding. read(65536) requests at most that many bytes; the final chunk can be smaller.

  2. 2

    The assignment expression stores each chunk and checks whether it is nonempty. Empty bytes signal end of file.

  3. 3

    update() can be called repeatedly. The resulting digest matches hashing the entire content in one operation, provided the bytes and order are identical.

04 Your turn, builder

A SMALL MISSION

Hash the same bytes in two chunks and confirm the digest equals a one-shot hash.

Reveal one possible solution +
one_possible_solution.py
import hashlib
parts = hashlib.sha256()
parts.update(b"ab")
parts.update(b"c")
print(parts.digest() == hashlib.sha256(b"abc").digest())

05 Check your signal

QUICK SIGNAL CHECK

Why use rb for an image?

THAT’S ANOTHER IDEA IN YOUR TOOLKIT.

Experiment. Logged.

When you can explain the idea and make the example your own, mark it complete. Your log stays in this browser.

Keep exploring

Go deeper with the official Python guide ↗.

Built with curiosity. By Navan Sami. ↗Python 3 · Think. Try. Build.