Advertisement
Open Source Projects by Phil Schwartz

Safe File Renaming with Python pathlib

My open-source work includes DenyHosts, Kodos and Scratchy: focused utilities that solve operational problems without becoming oversized frameworks. A file renamer belongs in that same family. It needs a narrow purpose, visible safeguards and behaviour that another developer can inspect.

Renaming files can look trivial until a shared drive contains two similarly named reports, a USB device uses a case-insensitive filesystem, or a filename accidentally reveals a client’s name. Using Python’s pathlib to build a safe file renaming function with dry-run mode keeps those risks visible before anything on disk changes.

Why pathlib suits rename operations

Python’s pathlib represents paths as objects rather than interchangeable strings. Path.with_name() produces a sibling destination, Path.iterdir() enumerates a directory consistently, and Path.exists() handles platform-specific path rules. These methods make the intended operation easier to read and test.

That portability matters in Australian workplaces, where a Sydney office may run Windows laptops while a Melbourne team maintains Linux servers. The same pathlib code can inspect both environments, although filesystem semantics still need local testing. A path library standardises the interface; it does not erase differences between NTFS, APFS and ext4.

Defining a conservative safety contract

Before writing code, decide what “safe” means. This version accepts an existing source file and a new basename, keeps both paths in the same directory, rejects separators and control characters, refuses to overwrite an existing destination, and defaults to preview-only behaviour. It returns a structured result so callers can log the proposed change.

The contract should also cover the organisation around the code. For an Australian organisation covered by the Privacy Act 1988, the Australian Privacy Principles may make a revealing filename a data-governance problem. Renaming is not anonymisation, and names alone can still disclose personal information. Sensible logs and access controls remain necessary.

Implementing the dry-run function

Here is a small implementation with the safety decisions visible in one place:

from dataclasses import dataclass
from pathlib import Path

@dataclass(frozen=True)
class RenameResult:
    source: Path
    destination: Path
    changed: bool

def safe_rename(source: str | Path, new_name: str, *,
                dry_run: bool = True) -> RenameResult:
    src = Path(source).expanduser()
    if not src.exists():
        raise FileNotFoundError(src)
    if not src.is_file():
        raise ValueError(f"Not a file: {src}")
    if not new_name or new_name in {".", ".."}:
        raise ValueError("Invalid destination name")
    if "/" in new_name or "\\" in new_name:
        raise ValueError("Use a filename, not a path")
    if any(ord(char) < 32 for char in new_name):
        raise ValueError("Control characters are not allowed")

    dst = src.with_name(new_name)
    if src.absolute() == dst.absolute():
        return RenameResult(src, dst, False)
    if dst.exists() or dst.is_symlink():
        raise FileExistsError(dst)

    if dry_run:
        return RenameResult(src, dst, False)

    src.rename(dst)
    return RenameResult(src, dst, True)

With dry_run=True, the function validates the request and returns the intended paths but leaves the source untouched. Setting it to False performs the rename and reports that a change occurred. The default favours inspection, while the explicit flag separates preview from execution.

Preventing collisions before mutation

A dry run is most valuable when it checks the whole batch. If two source files would become invoice-final.pdf, checking each destination separately can miss the conflict until the first rename succeeds. Build a complete plan first, store proposed destinations in a set, reject duplicates, and only then apply changes. This prevents a partially renamed folder.

Several edge cases deserve explicit policy. Case-only changes need a temporary intermediate name on case-insensitive volumes; Unicode normalisation varies across macOS and Linux; exFAT USB drives used by Australian schools, clubs and sole traders may impose different length and character limits. Resolve those cases deliberately rather than hiding them behind generic error messages.

That check is not atomic: Path.rename() can replace a destination created after validation on some systems. Restrict the directory to one writer, or use an operating-system no-replace primitive when concurrent changes are possible.

Connecting the function to a command line

A reusable library function becomes more practical when its dry-run mode is visible on the command line. An argparse interface can accept a directory and pattern, print source -> destination for every proposal, and require an --apply flag before mutating files. Exit non-zero when validation fails so shell scripts and scheduled jobs notice the problem.

For teams using a shared NAS drive, save the preview output with the job record before applying it. Small businesses and community organisations often rely on these shared folders, and an auditable list makes a mistaken rule easier to trace. The tool should refuse to continue after a collision instead of guessing which file should win.

Testing with realistic file trees

Tests should prove both the refusal and the no-change promise:

def test_dry_run_leaves_file(tmp_path):
    source = tmp_path / "old name.txt"
    source.write_text("hello", encoding="utf-8")
    result = safe_rename(source, "new name.txt")
    assert result.destination.name == "new name.txt"
    assert source.exists()
    assert not result.changed

def test_existing_destination_is_rejected(tmp_path):
    source = tmp_path / "source.txt"
    other = tmp_path / "target.txt"
    source.touch()
    other.touch()
    try:
        safe_rename(source, other.name)
    except FileExistsError:
        pass
    else:
        raise AssertionError("Expected FileExistsError")

def test_apply_moves_file(tmp_path):
    source = tmp_path / "source.txt"
    source.touch()
    result = safe_rename(source, "target.txt", dry_run=False)
    assert result.changed
    assert not source.exists()
    assert (tmp_path / "target.txt").exists()

Run the suite on NTFS, APFS, Linux filesystems and an exFAT drive used for real transfers. Include spaces, accents, long names, symlinks and case-only changes. On network shares, add tests for stale entries and temporarily unavailable files; local assumptions do not guarantee consistent behaviour there.

Publishing it as a focused utility

Packaging the tool with a README, example output, version information, an SPDX licence identifier and a short changelog makes it suitable for a public repository. The README should state that dry-run is the default, that destinations found during validation are rejected and that the destination stays beside the source. Those guarantees are more useful than a long feature list.

Distribution is simpler when the utility depends only on Python’s standard library. Readers comparing lightweight open-source tools can also consult FoldYouS resources when evaluating alternative implementations and release packaging. Keep this renamer separate from larger applications, as DenyHosts, Kodos and Scratchy each retain a clear purpose.

This combination of pathlib, conservative defaults and observable previews turns an ordinary maintenance task into dependable software. It also suits the wider portfolio: small tools that Australian developers can inspect, run locally and adapt without surrendering control of their files.