πŸŽ‰ 75% of content is free forever β€” Unlock Premium from $10/mo β†’
CW
NEWSLIVESearch All Content
πŸ’Ό Servicesℹ️ Aboutβœ‰οΈ ContactView Pricing Plansfrom $10

Python Files: Binary, mmap, and Temporary Storage

Python File I/O🟒 Free Lesson

Python Files: Binary, mmap, and Temporary Storage

File handling stops being trivial the moment the data is larger than memory, not encoded in the platform default, or must be replaced without a reader ever seeing a half-written version. Those three conditions cover most production scripts: log rotation, CSV imports, image pipelines, and configuration updates. Python's standard library has a tool for each β€” text mode with an explicit encoding, generators that stream lines, struct for fixed-width records, mmap for random access, tempfile for scratch space, and os.replace for atomic commits β€” but they only compose correctly when you know which layer owns which responsibility. This lesson works through them in that order.

What You'll Learn

  • 1Choose text or binary mode and set encoding explicitly at every boundary
  • 2Stream files of any size with generators instead of readlines
  • 3Pack and unpack fixed-width binary records with struct
  • 4Write atomically and manage scratch files with tempfile

Encoding decisions belong at the boundary

Text mode decodes bytes into strings using an encoding, and if you do not name one, you inherit the platform default β€” which differs between a developer laptop and a server, and between Python versions. The fix is to pass encoding="utf-8" on every open of text, and to treat errors as a deliberate policy: strict for data you must reject, replace for logs and previews where a visible placeholder beats a crash, and surrogateescape for round-tripping bytes you cannot fully decode.

Binary mode performs no decoding at all, which is what image, archive, and compiled data require. The trap is mixing them: writing bytes to a text handle or vice versa raises immediately, while appending text to a file opened elsewhere in binary silently corrupts it if the encoding uses multi-byte characters. Normalise line endings yourself with newline="" when parsing files from other platforms, because universal newline translation will otherwise hide the difference between CRLF and LF and break offset calculations.

python
import io

with open("sample.txt", "w", encoding="utf-8", newline="\n") as handle:
    handle.write("caf\u00e9\nna\u00efve\n")

with open("sample.txt", encoding="utf-8") as handle:
    print(handle.read().splitlines())      # ['cafΓ©', 'naΓ―ve']

with open("sample.txt", encoding="utf-8", errors="replace") as handle:
    raw = handle.read()

payload = "Ο€ is 3.14159".encode("utf-8")
print(payload, len(payload))               # b'\xcf\x80 is 3.14159' 14
print(payload.decode("utf-8", "strict"))   # Ο€ is 3.14159

buffer = io.StringIO("a,b\nc,d\n")
print([line.strip() for line in buffer])   # ['a,b', 'c,d'] β€” same API, no disk

io.StringIO and io.BytesIO implement the same interface as file objects, which is worth remembering: any function written against a file handle can be tested without touching the filesystem, simply by passing a buffer.

Streaming files that do not fit in memory

handle.read() loads everything, and handle.readlines() is the same mistake with a list wrapped around it. A file object is itself an iterator, so a plain for line in handle yields one line at a time and keeps memory flat regardless of file size. The memory profile of that loop is roughly one line plus whatever you accumulate, which is the difference between processing a 40 GB log on a laptop and running out of heap halfway through.

Two details separate robust streaming from code that works on samples. First, strip newlines explicitly rather than relying on rstrip(), which will happily delete trailing whitespace that is part of the data β€” use rstrip("\n") or rstrip("\r\n"). Second, keep parsing inside the generator and yield structured records, so the caller never sees raw lines. When you need random access into a large file, iteration is the wrong tool and mapping is the right one, which the next section covers.

python
import csv
import itertools

def stream_rows(path):
    with open(path, encoding="utf-8", newline="") as handle:
        reader = csv.DictReader(handle)
        for line_number, row in enumerate(reader, start=2):
            yield line_number, row

def grep(path, needle, limit=None):
    count = 0
    with open(path, encoding="utf-8", errors="replace") as handle:
        for number, line in enumerate(handle, start=1):
            if needle in line:
                yield number, line.rstrip("\r\n")
                count += 1
                if limit and count >= limit:
                    return

def head(path, n):
    with open(path, encoding="utf-8") as handle:
        yield from itertools.islice(handle, n)

for number, line in grep("sample.txt", "na", limit=5):
    print(number, line)

The limit parameter in grep is the detail that keeps the generator honest: it stops reading as soon as enough matches are found, so a search across a terabyte for the first hit costs one read rather than a full scan. Generators compose for free β€” chain head, grep, and a parser and the whole pipeline still streams.

Fixed-width records with struct

Not everything on disk is text. Sensor logs, database page files, and network frames often store fixed-width fields, and parsing them with slicing works only as long as the layout never changes. The struct module reads the layout declaratively, converts in C, and lets you compute the exact record size so iteration becomes arithmetic rather than guesswork.

Format strings describe byte order, field types, and alignment. Big-endian layout uses > and little-endian uses <; the I code is an unsigned int and f a float. Always record the layout alongside the data β€” a constants module, a version header, or a sidecar schema β€” because a format string with no documented byte order is a puzzle that cannot be solved from the file alone.

python
import struct

HEADER = struct.Struct(">I f 4s")     # big-endian: uint, float, 4 bytes tag
print(HEADER.size)                    # 12 bytes per record

def pack_records(rows):
    return b"".join(HEADER.pack(seq, value, tag.encode("ascii")[:4].ljust(4, b"\0"))
                    for seq, value, tag in rows)

def unpack_records(blob):
    for offset in range(0, len(blob), HEADER.size):
        seq, value, tag = HEADER.unpack_from(blob, offset)
        yield seq, value, tag.rstrip(b"\0").decode("ascii")

payload = pack_records([(1, 3.5, "temp"), (2, 9.9, "pres")])
print(len(payload), list(unpack_records(payload)))
# 24 [(1, 3.5, 'temp'), (2, 9.9, 'pres')]

print(struct.unpack(">2I", struct.pack(">2I", 7, 8)))   # (7, 8)

The ljust(4, b"\0") padding shows the discipline binary formats require: fixed fields need fixed length, so short tags are padded and long ones must be truncated or rejected. Choosing truncation silently is how a tag becomes a different tag β€” validate instead.

Memory mapping for random access

mmap maps a file into the process address space, letting you index and slice it like bytes without reading it all into Python objects. For a multi-gigabyte file queried at scattered offsets, mapping beats repeated seek and read because the operating system loads and evicts pages on demand, reusing the same cache it already maintains for the file.

The technique suits read-only lookup tables, index files, and formats you slice manually. It is a poor fit for files that grow while mapped, for very small files where the setup cost dominates, and for code that needs decoded Python objects rather than bytes β€” a mapped file gives you bytes, and every field you extract still needs unpacking. Close the mapping promptly, since it holds a file descriptor and, on Windows, prevents the file from being renamed or deleted while open.

python
import mmap
import os

with open("sample.bin", "wb") as handle:
    handle.write(b"IDX" + b"\0" * 5 + b"payload-records-here")

with open("sample.bin", "r+b") as handle:
    with mmap.mmap(handle.fileno(), 0, access=mmap.ACCESS_READ) as view:
        print(view[:3])                 # b'IDX'
        print(view.find(b"payload"))    # 8
        print(view[8:15])               # b'payload'
        print(len(view))                # 26 β€” file size, no copy made
        print(view[3:8])                # b'\x00\x00\x00\x00\x00'

print(os.path.getsize("sample.bin"))    # 26

Note the nested with: the file handle must outlive the mapping, and the mapping must be closed before the handle closes. Reversing that order produces a BufferError on some platforms, which is a useful reminder that the mapping is a live reference to the file rather than a copy of its contents.

Temporary files without leftovers

Scratch files are where scripts leak disk space and, occasionally, secrets. tempfile creates names that cannot be guessed by another process, places them in the system temp directory, and removes them on close. NamedTemporaryFile is right when a single file is needed; TemporaryDirectory is right when the work needs several files or a directory structure; both guarantee cleanup when used as context managers.

Two behavioural details cause most surprises. NamedTemporaryFile with delete=False keeps the file after closing, which is necessary when another program must open it by name β€” but then deleting it becomes your responsibility, and forgetting that step leaves data behind. And passing delete=False to keep a file for a later step defeats the purpose if the process crashes in between: prefer writing to a temporary location and promoting it atomically, which the next section makes concrete.

python
import os
import tempfile

def build_report(rows):
    directory = tempfile.mkdtemp(prefix="report-")
    path = os.path.join(directory, "report.txt")
    try:
        with open(path, "w", encoding="utf-8") as handle:
            for row in rows:
                handle.write(f"{row}\n")
        with open(path, encoding="utf-8") as handle:
            return handle.read()
    finally:
        import shutil
        shutil.rmtree(directory, ignore_errors=True)

print(build_report(["alpha", "beta"]).splitlines())   # ['alpha', 'beta']

with tempfile.NamedTemporaryFile(mode="w+", suffix=".json", delete=False) as tmp:
    tmp.write('{"ok": true}')
    name = tmp.name
print(os.path.exists(name))     # True β€” delete=False leaves it behind
os.remove(name)                 # cleanup is now your job

Prefer the context-managed forms in application code. The delete=False variant exists for interoperability with external tools, and every use of it should be paired with an explicit removal on every exit path, including the exception ones.

Atomic writes and choosing the right API

A writer that truncates a file and then fills it creates a window in which readers see empty or partial data, and a crash during that window leaves the file permanently damaged. The standard fix is write-then-rename: create a temporary file in the same directory, flush and fsync it, then os.replace onto the target. Replacement is atomic on POSIX and on Windows, so readers observe either the old file or the complete new one.

The rest of the API surface is a matter of picking the layer that matches the task. Low-level os calls control descriptors and permissions, pathlib expresses paths as objects, glob and pathlib.glob find files by pattern, and csv and json handle parsing better than manual splitting ever will. The table below maps the common jobs to the module that should own them.

JobModule or APIWhy it wins
Read or write text with an encodingopen with encoding=Explicit, streamable, universal
Build and join pathspathlib.PathObjects, readable, cross-platform
Find files by patternglob.glob or Path.globRecursive search without os.walk boilerplate
Structured tabular datacsv.DictReaderHandles quoting and embedded commas
Nested configurationjson.loadRound-trips dictionaries and lists
Scratch storagetempfileSafe names, automatic cleanup
Replace a file safelyos.replaceAtomic swap within one filesystem
Walk a directory treeos.walk or Path.rglobYields paths without loading everything
python
import json
import os
import pathlib
import tempfile

def atomic_write_json(path, payload):
    target = pathlib.Path(path)
    handle = tempfile.NamedTemporaryFile(
        "w", encoding="utf-8", dir=target.parent, suffix=".tmp", delete=False
    )
    try:
        with handle:
            json.dump(payload, handle, indent=2, sort_keys=True)
            handle.flush()
            os.fsync(handle.fileno())
        os.replace(handle.name, target)
    except BaseException:
        os.unlink(handle.name)
        raise

atomic_write_json("sample.json", {"status": "ok", "count": 3})
print(json.loads(pathlib.Path("sample.json").read_text(encoding="utf-8")))

found = sorted(p.name for p in pathlib.Path(".").glob("sample.*"))
print(found)     # ['sample.bin', 'sample.json', 'sample.txt']

The except BaseException clause matters: cleanup must run for KeyboardInterrupt and SystemExit too, otherwise an interrupted run strands a temporary file in the target directory. And dir=target.parent keeps the temporary on the same filesystem, without which os.replace can fail with a cross-device error.

Common Mistakes

Calling open on text files without specifying an encoding

Fix: Pass encoding="utf-8" explicitly so behaviour does not change between machines

Reading an entire file with read() because the sample was small

Fix: Iterate the file object and process one line at a time so memory stays flat at any size

Using delete=False in NamedTemporaryFile without a guaranteed cleanup path

Fix: Delete in a finally block, or write to a temp location and promote it with os.replace

Truncating a live file and rewriting it in place

Fix: Write a sibling temporary file, fsync it, then os.replace so readers never see partial data

Parsing CSV or JSON with split and manual string handling

Fix: Use the csv and json modules, which handle quoting, escapes, and embedded newlines

Best Practices

  • Name encoding and newline policy at every file boundary, never relying on the default
  • Keep parsers in generators so callers stream instead of accumulating
  • Document the byte order and layout next to any struct format string
  • Use tempfile for scratch work and promote results atomically with os.replace
  • Close mappings before closing their file handle, and prefer context managers throughout

Interview Questions

Q1: How do you copy a file without loading it into memory?

Iterate in chunks with shutil.copyfileobj or read and write fixed-size blocks in a loop. For same-filesystem moves use os.replace or os.rename, which do not copy at all.

Q2: Why might os.replace be necessary instead of opening the target for writing?

Opening for writing truncates first, exposing readers to empty or partial content and risking corruption on a crash. os.replace atomically swaps a fully written temporary file onto the target, so readers see the old version or the new one, never an intermediate state.

Q3: When is mmap a poor choice?

When files are tiny, when they must grow while mapped, or when you need decoded Python objects rather than raw bytes. Mapping also holds a descriptor open, which can block deletion or renaming on Windows.

Key Takeaways

  • Set encoding explicitly; platform defaults differ across machines and versions
  • File objects are iterators β€” stream with for line in handle and keep memory flat
  • struct gives declared, C-speed parsing for fixed-width records when the layout is documented
  • mmap provides demand-paged random access without copying the file into Python objects
  • Write to a temporary, fsync, then os.replace for updates readers must never see half-done
CW

ChatWhole Learn Editorial Team

Written by experienced data scientists, software engineers, and educators. All content is reviewed by industry professionals to ensure accuracy and relevance.

Last reviewed: 2026-10-12

β€”
β˜†β˜†β˜†β˜†β˜†
0 ratings

Rate & Feedback

Continue Learning

Suggested next tutorials based on this topic

Need Expert Python Help?

Get personalized tutoring, project support, or professional consulting.

Advertisement