the full guide

Binary files and images

Binary mode ("rb" and "wb") reads and writes raw bytes with no text conversion. It's needed for images, audio, models and any other non-text file.

6 min Intermediate

What you need: The earlier topics of this module.

Definition

Binary mode ("rb" and "wb") reads and writes raw bytes with no text conversion. It's needed for images, audio, models and any other non-text file.

In simple words

Text mode treats a file as letters, and binary mode treats it as plain numbers from 0 to 255. A photo isn't letters, so reading it as text gives an error or garbage.

Why it matters

AI work is full of binary files, including images, audio and saved model weights. Understanding bytes also helps when you need to send files through APIs.

How it works

In code

binary.py
import tempfile
from pathlib import Path

with tempfile.TemporaryDirectory() as folder:
    path = Path(folder) / "data.bin"

    with open(path, "wb") as f:
        f.write(bytes([137, 80, 78, 71, 13, 10, 26, 10]))

    with open(path, "rb") as f:
        data = f.read()

    print("Size:", len(data), "bytes")
    print("First byte:", data[0])
    print("As hex:", data[:4].hex())
    print("Looks like PNG:", data[:4] == b"\x89PNG")

Output

Size: 8 bytes
First byte: 137
As hex: 89504e47
Looks like PNG: True

Common mistakes

  • Opening a binary file in text mode, which gives a decode error.
  • Giving an encoding in binary mode. That's an error, as bytes have no encoding.

Check yourself

Question 1

1. What does f.read() return in "rb" mode?

Question 2

2. Which mode suits an image?

Summary

  • Use "rb" and "wb" for non-text files.
  • You get bytes, numbers from 0 to 255.

Finished reading?

Sources: The Python Tutorial, python.org