Python Files, Paths, CSV and JSON · Lesson 109 of 149

Python Binary Files and pickle

What you will learn

  • Bytes versus text; encoding and decoding
  • Binary modes "rb" and "wb"
  • Copying and hashing files in chunks
  • A look at struct for fixed binary layouts
  • pickle: saving Python objects
  • Why pickle can be dangerous, and what to use instead

1. Bytes and text

Everything on a disk is bytes: numbers from 0 to 255. Text is a layer on top: an encoding (such as UTF-8) says which bytes mean which characters. Python keeps the two apart with two types:

Type Holds Written as
str characters "café"
bytes numbers 0 to 255 b"caf\xc3\xa9"
b = bytes([72, 101, 108, 108, 111])
print(b, b[0], list(b), type(b), len(b))
print(b.decode("utf-8"))
b'Hello' 72 [72, 101, 108, 108, 111] <class 'bytes'> 5
Hello
  • Indexing bytes gives integers, not one-byte strings.
  • .decode(encoding) turns bytes into text; .encode(encoding) goes the other way.
print("café".encode("utf-8"))
print(len("café"), len("café".encode("utf-8")))
b'caf\xc3\xa9'
4 5

The word has 4 characters but takes 5 bytes, because é needs two bytes in UTF-8. That is why a text file's size in bytes can differ from its number of characters.

bytes is immutable, like str. Its changeable twin is bytearray:

ba = bytearray(b)
ba[0] = 74
print(ba, bytes(ba))
bytearray(b'Jello') b'Jello'

(Assigning to a bytes object fails: TypeError: 'bytes' object does not support item assignment.)

Quick check: what is `b"AB"[0]`?

65, an integer (the code of the letter A).

2. Binary mode: "rb" and "wb"

Add b to the mode to work with raw bytes: "rb", "wb", "ab". In binary mode there is no encoding and no newline conversion: you get exactly the bytes in the file. Do not pass encoding.

with open("data.bin", "wb") as f:
    n = f.write(bytes(range(10)) + b"\x00\xff")
print(n)

with open("data.bin", "rb") as f:
    print(f.read(4))
    print(f.read(3))
    print(list(f.read()))
12
b'\x00\x01\x02\x03'
b'\x04\x05\x06'
[7, 8, 9, 0, 255]
  • write returns the number of bytes written.
  • read(n) reads n bytes; read() reads the rest. Binary files can be read in pieces, like text files.

Mixing the modes up gives errors that tell you what is wrong:

with open("other.bin", "w") as f:
    f.write(b"x")
TypeError: write() argument must be str, not bytes

And opening a binary file as text usually fails because the bytes are not valid text:

with open("data.bin", encoding="utf-8") as f:
    f.read()
UnicodeDecodeError: 'utf-8' codec can't decode byte 0xff in position 11: invalid start byte

Use binary mode for anything that is not plain text: images, audio, PDFs, zip files, executables, and files from other programs. Path.read_bytes() and Path.write_bytes() (lesson 15.4) are shortcuts for small files.

3. Large files in chunks

To copy or process a big file without loading it all into memory, read it in chunks with the walrus operator (:=, lesson 5.6):

def copy_file(src, dst, chunk_size=1024):
    with open(src, "rb") as a, open(dst, "wb") as b:
        while chunk := a.read(chunk_size):
            b.write(chunk)

The loop ends when read returns the empty bytes b"" (end of file). The same pattern computes a checksum, a short fingerprint used to check that two files are identical:

import hashlib

def sha256_of(path):
    h = hashlib.sha256()
    with open(path, "rb") as f:
        while chunk := f.read(1024):
            h.update(chunk)
    return h.hexdigest()

Two files with the same SHA-256 are, for practical purposes, identical. For plain copies, shutil.copy (lesson 15.5) does all this for you.

4. Fixed layouts: struct

Many file formats pack numbers into exact byte positions. The struct module converts between Python numbers and such bytes:

import struct

packed = struct.pack("<Hf", 513, 1.5)
print(packed, len(packed))
print(struct.unpack("<Hf", packed))
print(struct.calcsize("<Hf"))
b'\x01\x02\x00\x00\xc0?' 6
(513, 1.5)
6

The format string "<Hf" means: < little-endian byte order, H an unsigned 2-byte integer, f a 4-byte float. This is advanced and needed only when you read or write a specific binary format. Also useful: int.from_bytes(b"\x00\x01", "big") is 1, and (258).to_bytes(2, "little") is b'\x02\x01'.

5. pickle: saving Python objects

pickle saves almost any Python object to bytes and restores it later, including sets, tuples, dates and your own classes. It writes binary files:

import pickle
import datetime

obj = {"name": "Rina", "scores": [80, 90], "set": {1, 2}, "t": (1, 2),
       "when": datetime.date(2026, 3, 1)}

blob = pickle.dumps(obj)
print(type(blob), pickle.loads(blob) == obj, pickle.loads(blob)["t"])

with open("o.pkl", "wb") as f:
    pickle.dump(obj, f)
with open("o.pkl", "rb") as f:
    print(pickle.load(f) == obj)
<class 'bytes'> True (1, 2)
True

Compare with JSON (lesson 15.7): everything came back exactly, including the set, the tuple and the date. Your own classes work too:

class Pt:
    def __init__(self, x):
        self.x = x

    def __repr__(self):
        return f"Pt({self.x})"

print(pickle.loads(pickle.dumps(Pt(3))))
Pt(3)

(The class must be importable when loading.) The function names mirror JSON: dump/load for files, dumps/loads for bytes.

What cannot be pickled

Open files, sockets, locks and lambdas have no saved form:

pickle.dumps(lambda x: x)
PicklingError: Can't pickle <function <lambda> at 0x000001BA73A4F420>: attribute lookup <lambda> on __main__ failed

(The address differs on every run; the point is that a lambda cannot be pickled.) Likewise pickle.dumps(open("data.bin", "rb")) raises TypeError: cannot pickle 'BufferedReader' instances.

6. The danger of pickle

Never unpickle data from a source you do not fully trust.

Unpickling does not just rebuild data: it can run code. A harmless demonstration, where loading a pickle makes Python call print:

class Evil:
    def __reduce__(self):
        return (print, ("this ran during load!",))

pickle.loads(pickle.dumps(Evil()))
this ran during load!

Replace print with any other command and a hostile pickle file could do real harm to your computer. Therefore:

  • Use pickle only for data your own program wrote and nobody else can change.
  • Never load pickles received from the internet, email or other users.
  • The format can change between Python versions and is Python-only, so it is a poor choice for long-term storage or for sharing.

7. Safer alternatives

Need Better choice
settings and simple records JSON (lesson 15.7)
tables CSV (lesson 15.6) or a database such as sqlite3 (lesson 17.10)
data shared with other languages JSON, CSV, or a documented format
large arrays of numbers a library format such as NumPy's .npy
caching a result for your own use pickle is acceptable, if the file is private
copying a nested object copy.deepcopy (lesson 7.5), not pickle

A game's save file shows the trade-off:

Worked example: copying, checking and saving state

First a chunked copy with a checksum comparison (and what a one-byte change does). Then a game state saved twice: with pickle, which needs no conversion but must be trusted, and with JSON, which needs the set turned into a list and back, but is safe to share.

import hashlib
import json
import pickle
from pathlib import Path


def copy_file(src, dst, chunk_size=1024):
    with open(src, "rb") as a, open(dst, "wb") as b:
        while chunk := a.read(chunk_size):
            b.write(chunk)


def sha256_of(path):
    h = hashlib.sha256()
    with open(path, "rb") as f:
        while chunk := f.read(1024):
            h.update(chunk)
    return h.hexdigest()


Path("pic.bin").write_bytes(bytes(range(256)) * 20)
copy_file("pic.bin", "pic_copy.bin", chunk_size=100)
print(Path("pic_copy.bin").stat().st_size, sha256_of("pic.bin") == sha256_of("pic_copy.bin"))

Path("pic_copy.bin").write_bytes(Path("pic_copy.bin").read_bytes()[:-1] + b"\x00")
print(sha256_of("pic.bin") == sha256_of("pic_copy.bin"))

state = {"level": 3, "items": ["key", "map"], "seen": {1, 2, 3}}
Path("save.pkl").write_bytes(pickle.dumps(state))
print(pickle.loads(Path("save.pkl").read_bytes()) == state)

safe = {"level": state["level"], "items": state["items"], "seen": sorted(state["seen"])}
Path("save.json").write_text(json.dumps(safe), encoding="utf-8")
back = json.loads(Path("save.json").read_text(encoding="utf-8"))
back["seen"] = set(back["seen"])
print(back == state)
5120 True
False
True
True
Step What it shows
copy in 100-byte chunks works for files of any size; 5120 bytes arrive
equal checksums the copy is identical
changing the last byte from 0xff to 0x00 the checksum differs, so tampering or damage is detected
pickle round trip the set survives with no conversion code
json round trip the set is stored as a sorted list, and rebuilt on loading; the file is readable and safe

The data is made up. Use the JSON version when others might touch the file.

Common mistakes

  • Opening a binary file as text (or the reverse), or passing encoding to a binary mode.
  • Writing str to a binary file (encode first).
  • Using "wb" and wiping an important file.
  • Loading pickles from untrusted sources.
  • Using pickle for long-term storage or sharing with other languages.
  • Reading a huge file with a single read().
  • Forgetting that one character may be several bytes.

Key takeaways

  • bytes hold raw numbers; str holds characters; encode and decode convert between them.
  • Binary modes "rb" / "wb" give exact bytes with no encoding and no newline changes; use them for non-text files.
  • Process large files in chunks with while chunk := f.read(n); use SHA-256 to compare files.
  • pickle saves almost any Python object but runs code on loading: only unpickle data you trust.
  • Prefer JSON, CSV or a database for data that is shared, long-lived or from others.

Practice

1. What is the difference between str and bytes?

Show answer

str is text (characters); bytes is raw data (numbers 0 to 255). They are converted with encode and decode.

2. Why is len("café") different from len("café".encode("utf-8"))?

Show answer

é takes two bytes in UTF-8, so the text has 4 characters but 5 bytes.

3. Which mode would you use to copy an image file?

Show answer

"rb" for the source and "wb" for the destination.

4. Why is it risky to call pickle.load on a file from the internet?

Show answer

Unpickling can execute arbitrary code, so a crafted file can run harmful commands on your computer.

5. Which loses less information when saving a set: pickle or json?

Show answer

pickle restores a set exactly. JSON has no sets, so you must convert to a list and back.

6. What does the loop while chunk := f.read(4096): do?

Show answer

It reads the file 4096 bytes at a time and stops when read returns empty bytes (end of file).