You are currently viewing Python Rename Files Dry Run: Preview and Check Collisions
Review the proposed filenames before applying the rename.

Python Rename Files Dry Run: Preview and Check Collisions

  • Post author:
  • Post published:
  • Post category:Python

A Python dry run should show the folder and the exact old and new names, then stop before changing a file. Check the whole plan for conflicts, even if you only expect to rename a few items. Once the plan looks right, run it on a disposable copy and compare the result with the preview. A successful run on one file tells you little about whether the second file’s destination is already occupied.

This example makes one predictable change. It replaces the draft_ prefix with ready_ for text files in a single folder. A dry run works on any platform with suitable permissions to list the folder. Applying the changes is limited to Windows, where Python’s rename operation refuses an existing destination. That limitation is part of the behaviour, and a useful reason to understand the platform before adapting a rename script.

Start with a folder you can recreate

Create a new working folder, save the Python file below in it, and make a folder called rename-demo inside it. Put two files called draft_notes.txt and draft_summary.txt in the demo folder. Give them different short contents so you can verify which file ended up under each name. Add an unrelated keep.txt or a subfolder if you want to check that the filter leaves those items alone.

Run commands from the directory containing the script and the demo folder. In Explorer, enable filename extensions when creating the test files so you can see whether an editor appended an extra .txt. If Python itself is unfamiliar, run a first Python script on Windows before working with a file operation. A sandbox copy lets you repeat the exercise without deciding how to undo changes to the originals.

Save a preview-first renamer

Save the code as rename_demo.py. It reads the folder entries together so the list used to plan names is separate from the loop that might change them. It skips symbolic links and directories and leaves other extensions and prefixes alone. Sorting is only for predictable output. A different sort order would produce the same destination names because the names come from the source suffix after the prefix, rather than a counter.

import argparse
import os
from pathlib import Path

def make_plan(folder):
    entries = sorted(folder.iterdir(), key=lambda p: (p.name.casefold(), p.name))
    occupied = {p.name.casefold() for p in entries}
    planned = set()
    moves = []
    for source in entries:
        if source.is_symlink() or not source.is_file():
            continue
        if not source.name.startswith("draft_") or source.suffix.lower() != ".txt":
            continue
        tail = source.name.removeprefix("draft_")
        target = source.with_name("ready_" + tail)
        key = target.name.casefold()
        if key in occupied or key in planned:
            raise ValueError(f"Destination conflict: {target.name}")
        planned.add(key)
        moves.append((source, target))
    return moves

def main():
    parser = argparse.ArgumentParser(description="Preview draft_ to ready_ renames.")
    parser.add_argument("folder", type=Path)
    parser.add_argument("--apply", action="store_true")
    args = parser.parse_args()
    if args.apply and os.name != "nt":
        parser.error("--apply is available only on Windows")
    try:
        folder = args.folder.resolve(strict=True)
        if not folder.is_dir():
            parser.error("folder must be a directory")
        moves = make_plan(folder)
    except (OSError, ValueError) as error:
        parser.exit(1, f"Plan stopped: {error}\n")

    print(f"Folder: {folder}", flush=True)
    for source, target in moves:
        print(f"{source.name} -> {target.name}", flush=True)
    if not args.apply:
        print(f"Dry run: {len(moves)} files proposed, zero files renamed.")
        return

    completed = 0
    for source, target in moves:
        try:
            source.rename(target)
        except OSError as error:
            parser.exit(1, f"Stopped after {completed} successful renames: {error}\n")
        completed += 1
        print(f"Renamed: {source.name} -> {target.name}", flush=True)
    print(f"Applied: {completed} files renamed.")

if __name__ == "__main__":
    main()

Run python .\rename_demo.py .\rename-demo. Expect to see the resolved folder path, followed by draft_notes.txt -> ready_notes.txt and draft_summary.txt -> ready_summary.txt. The last line should report two proposals and zero files renamed. Refresh Explorer or list the folder in your terminal. Both draft files should still be present, along with anything the script skipped.

Two filename changes are proposed and the dry run reports zero files renamed.
Check both proposed names and the containing folder before applying.

 

Review the folder path before looking at the new names. A relative folder argument points to the directory you used to launch the command, and the same name can exist in multiple projects. If the real folder contains spaces, quote the complete argument. Run the preview again after making any change to the files or to the rename rule. The apply command computes its own plan from current disk state, so a preview that scrolled past twenty minutes ago is a poor record of what an actively edited folder looks like now.

Understand what the plan checks

The destination is built with source.with_name(...), which substitutes a filename and preserves the containing directory. That call constructs a path without writing. The example copies the existing names into a set and compares candidates usingcasefold(), taking a conservative approach to names that differ only in letter case. It also remembers destination names already proposed during this run.

The code checks occupancy against every folder entry. If a directory, link, or an unrelated file already uses one of the requested names, the plan stops. The fixed draft_ and ready_ prefixes mean sources and destinations use distinct names in normal operation. The script deliberately avoids swaps such as one.txt to two.txt while two.txt is also a source. Swaps and overlapping chains need a different staging design if they are required.

If this were a sequential numbering script, a duplicate target check would matter even when all source names are unique. Different source names can produce the same target once you remove a prefix, lowercase a stem, or truncate it. Keep the checks together in the planning function if you change the rule. That way the program has a chance to report trouble before the first file moves.

Rehearse a collision before you apply

Create a separate test file named ready_notes.txt and put a short marker inside it. Run the exact same preview. The program should stop with Plan stopped: Destination conflict: ready_notes.txt. The original draft_notes.txt should remain, and reading the conflicting file should show its marker intact. The same conflict should stop an apply request before any rename begins.

The plan reports a destination conflict on ready_notes.txt and leaves both files in place.
A destination conflict stops the batch before any rename.

 

Now use a fresh copy of the demo folder without that conflicting file. Run preview again and check both mapping lines. On Windows, run python .\rename_demo.py .\rename-demo --apply once the plan in that disposable folder is correct. You should see a success line per operation followed by the completed count. Inspect the contents of the two ready files and match them with the lines you put in the drafts. This check proves more than seeing new names in Explorer.

Repeat the preview after applying. A second run should propose zero files because none start with the required prefix. The unrelated file and subfolder should still be present. If you try the same apply command on another operating system, argument parsing rejects it before scanning the folder. You can still preview there, but apply belongs to the Windows filesystem behaviour this example relies on.

Know where the overwrite decision is made

The preflight prevents an already occupied name from reaching the operation. Between the preview and an apply run a destination can appear, and a destination can also appear between the apply command’s own check and a rename. A preflight that calls exists() right before a rename still has that timing gap. The Windows operation is what refuses an occupied name at the moment it attempts the change.

Python’s os.rename documentation describes the difference. Windows raises a file-exists error for an existing destination, while on Unix an existing destination file can be replaced if the operation is permitted. Path.rename uses the same platform semantics. Substituting replace() would ask for overwrite behaviour, which does not fit this rule. For a portable apply mode, use a platform-appropriate no-clobber design and verify its actual operating-system behaviour before opening that mode.

Two renames succeed and a second preview proposes zero files.
After applying, run the preview again to confirm no draft files remain in scope.

Keep the batch recoverable if a rename fails

An apply run can stop after moving one or more files. The loop reports each successful change as it happens and prints the completed count before reporting an operating-system error. That output is a practical place to start if you need to compare what moved with what is still present. It does not provide rollback. Plan in a quiet folder and keep a copy of files you need to preserve. If the folder is synchronized or actively used by another program, rehearse on a local copy outside that activity.

A permission failure can come from the folder, from how another program opened the source, or from a destination that became occupied. Close programs you know are using the fixture before trying again. If an apply stopped halfway, compare the current folder with the completed mappings and preview again before proceeding. Blindly undoing each line in reverse can run into a new occupant at the old name. Inspect both paths before moving anything back, and use the independent copy when the state is unclear.

If you want a durable record for a real task, save the preview output next to your test notes and retain the apply output as a separate file outside the renamed folder. A CSV mapping can be a useful format when you are comparing many names. CyboGeek’s standard-library CSV walkthrough shows why quoting is helpful when a filename contains commas. Keep the original and new name in separate columns so the mapping stays readable even when the names contain punctuation.

Diagnose a preview that lists zero files

Check the printed folder path and make sure it directly contains your test files. This script looks at one level. A folder named rename-demo inside another folder with the same name can leave you one level too high. The prefix is case-sensitive in the example, while suffix matching accepts .txt or uppercase equivalents. Draft_notes.txt therefore stays outside the plan. Keep that behaviour deliberate if you decide to support a different naming convention.

The preview also excludes directories and symbolic links. If you expected a shortcut to lead to a real text file, put a regular copy in the fixture instead. Keep the working example narrow until you can explain each mapping and each skipped file. Reaching a clean preview, a tested collision, and a second run that finds nothing to do is a reliable stopping point for this small renamer.

Decide what belongs in a production plan

Keep the naming rule and the folder scope explicit when sharing an automation script with someone else. The person who runs it should understand that this example changes a fixed prefix and leaves the rest of the name intact. If the real job needs to remove dates, change extensions, or reorder a set of numbered names, write down examples where the old and new forms look almost the same. Those pairs often reveal collisions that a happy-path example misses.

Try a separate fixture whose target is a directory rather than a file. Make a directory named ready_summary.txt beside draft_summary.txt and confirm that preview refuses it. The folder name is unusual, but the test demonstrates why the planner checks all entries rather than listing only the files it intends to rename.

Also compare the before and after contents of a text file or an unrelated file you expected to be skipped. Renaming changes the directory entry. It should preserve the contents of the renamed file in this same-folder exercise. Verifying which contents ended up under which destination is a better review than comparing the number of files alone. Keep a short record of the collision rehearsal and which fixture copy you applied before using a rule on a larger folder.