Skip to content
devtoolbox.cc

Python · Chapter 14 of 21

Python files and pathlib: read, write, stream and replace safely

15 min study · Examples checked with Python 3.14 and 3.15 ·

Files are how programs keep data after they exit and how they exchange it with other programs. Working with them means making four decisions explicit: where the file is (its path), what you want to do (read, write, append), how bytes become text (the encoding), and what happens if something fails halfway. This chapter covers each with pathlib, builds a word counter that handles files of any size, and ends with a safe way to replace an important file.

Build paths with pathlib

from pathlib import Path

notes = Path("data") / "week-1" / "notes.txt"
print(notes)                        # data/week-1/notes.txt (data\week-1\notes.txt on Windows)
print(notes.name, notes.stem, notes.suffix)   # notes.txt notes .txt
print(notes.parent, notes.with_suffix(".md")) # data/week-1 data/week-1/notes.md

notes.parent.mkdir(parents=True, exist_ok=True)

A Path object joins parts with / and uses the right separator for the operating system, so you never glue strings together with "/" or "\\". Its attributes split a path into name, stem, suffix and parent (suffixes gives ['.tar', '.gz'] for backup.tar.gz). mkdir(parents=True, exist_ok=True) creates every missing folder and doesn’t fail if they already exist.

Relative paths such as data/notes.txt are resolved against the current working directory, which is wherever the program was started from, not where the script lives. To find files that ship next to your code, build the path from the script’s location: Path(__file__).resolve().parent / "data".

Checking exists() before opening a file is less useful than it looks: another program can delete the file between the check and the open. Just open it and handle FileNotFoundError.

Open modes and encodings

from pathlib import Path

path = Path("journal.txt")
path.write_text("Day 1: variables\n", encoding="utf-8")

with path.open("a", encoding="utf-8") as f:     # append
    f.write("Day 2: loops\n")
    print("Day 3: functions", file=f)

with path.open(encoding="utf-8") as f:          # "r" is the default
    print(f.readline().rstrip())                # Day 1: variables
    print(f.read().splitlines())                # ['Day 2: loops', 'Day 3: functions']

The mode says what you intend. "r" reads an existing file. "w" creates the file or empties an existing one the moment it is opened, before you write anything. "a" appends to the end. "x" creates a new file and raises FileExistsError if one exists, which protects data you didn’t mean to overwrite. Adding "b" (as in "rb") switches to bytes. read_text and write_text are shortcuts that open, read or write, and close in one call.

A with block closes the file when it ends, even if an exception occurs, which also flushes buffered writes to disk. Never rely on Python closing files for you at some later point.

Always pass encoding="utf-8" unless you know a file uses something else. Python 3.15 makes UTF-8 the default everywhere, but older versions used the operating system’s preferred encoding, which on Windows is often not UTF-8, so the explicit argument keeps your code correct on every version. If a file from another system fails to decode, find out its real encoding instead of passing errors="ignore", which silently deletes characters.

Stream a large file line by line

Iterating over an open text file yields one line at a time, so memory use stays small however big the file is:

from collections import Counter
from pathlib import Path
import re

WORD = re.compile(r"[a-z']+")

def count_words(path: Path) -> Counter[str]:
    counts: Counter[str] = Counter()
    with path.open(encoding="utf-8") as f:
        for line in f:
            counts.update(WORD.findall(line.casefold()))
    return counts

sample = Path("sample.txt")
sample.write_text("Python is fun.\nPYTHON is readable, and fun!\n", encoding="utf-8")
for word, n in sorted(count_words(sample).items(), key=lambda kv: (-kv[1], kv[0]))[:3]:
    print(f"{word:<8}{n}")
# fun     2
# is      2
# python  2

The function only counts and returns; printing happens in the caller, so the same function works in a command-line tool or a test. The sort key orders by count descending and then alphabetically, which makes the output identical on every run. The regular expression is a simple definition of a word; real text with hyphens, other alphabets or numbers needs a more careful rule. Each line still ends with \n when read this way, so use line.rstrip("\n") when you need the text alone.

Bytes are not text

Images, PDFs, archives and other non-text files must be opened in binary mode, where you read and write bytes and no decoding happens:

from pathlib import Path
import shutil

original = Path("logo.bin")
original.write_bytes(bytes([0x89, 0x50, 0x4E, 0x47, 0, 255]))

with original.open("rb") as src, Path("logo-copy.bin").open("wb") as dst:
    shutil.copyfileobj(src, dst)            # copies in chunks

data = Path("logo-copy.bin").read_bytes()
print(data[:4], len(data), data == original.read_bytes())  # b'\x89PNG' 6 True

shutil.copyfileobj copies between open files in chunks, so it handles files bigger than memory. For whole files, shutil.copy2(src, dst) also copies timestamps, and since Python 3.14 Path.copy() and Path.move() do the same from a path object. Decoding binary data as text to “copy” it corrupts it.

Walk folders, rename and delete

from pathlib import Path

root = Path("course")
for name in ["intro.md", "loops.md", "draft/ideas.md", "draft/old.txt"]:
    (root / name).parent.mkdir(parents=True, exist_ok=True)
    (root / name).write_text(name, encoding="utf-8")

print(sorted(p.name for p in root.glob("*.md")))       # ['intro.md', 'loops.md']
print(sorted(str(p.relative_to(root)) for p in root.rglob("*.md")))
# ['draft/ideas.md', 'intro.md', 'loops.md']

old = root / "draft" / "old.txt"
old.rename(root / "draft" / "archive.txt")
(root / "draft" / "archive.txt").unlink()
print(sorted(p.name for p in (root / "draft").iterdir()))  # ['ideas.md']

glob matches names in one folder and rglob searches all subfolders. iterdir lists a folder’s direct contents. rename moves a file, unlink deletes a file, rmdir removes an empty folder, and shutil.rmtree deletes a whole tree, so use that one with care.

When a path comes from a user, for example a file name in a web request, never join it directly onto a folder: "../../etc/passwd" would escape it. Resolve the combined path and check it is still inside the allowed folder with resolved.is_relative_to(base.resolve()).

Replace an important file safely

Writing directly over a file that matters (a settings file, a database export) is risky: if the program crashes halfway, the old content is gone and the new content is incomplete. Write a temporary file in the same folder, then swap it in with one atomic operation:

import os
import tempfile
from pathlib import Path

def write_atomic(path: Path, text: str) -> None:
    fd, tmp = tempfile.mkstemp(dir=path.parent, prefix=path.name, suffix=".tmp")
    try:
        with os.fdopen(fd, "w", encoding="utf-8") as f:
            f.write(text)
            f.flush()
            os.fsync(f.fileno())
        os.replace(tmp, path)          # atomic on the same file system
    except BaseException:
        os.unlink(tmp)
        raise

settings = Path("settings.txt")
write_atomic(settings, "theme=dark\n")
print(settings.read_text(encoding="utf-8").strip())  # theme=dark

os.replace swaps the file in a single step, so other programs see either the complete old file or the complete new one. fsync asks the operating system to put the data on disk before the swap. If anything fails, the temporary file is removed and the original is untouched.

Practice

Turn count_words into a script that takes a file path from the command line (sys.argv[1] or argparse), prints the ten most common words, and prints a clear message and exits with status 1 if the file doesn’t exist or isn’t valid UTF-8.

Answer check: catch FileNotFoundError and UnicodeDecodeError separately so each gets its own message, for example cannot read notes.txt: no such file. Mixed case such as Python python counts as two occurrences of python, an empty file prints nothing, and the input file is never modified.

Summary

Use pathlib to build and inspect paths, and remember that relative paths depend on the working directory. Pick the mode deliberately ("w" empties a file at once, "x" refuses to overwrite), always name the encoding, and use with. Stream large files line by line, keep bytes as bytes, validate user-supplied paths, and replace important files atomically with os.replace.

All Python chapters