October DealsAmazon USOctober deal check: compare before you payAmazon US: current deals, useful picks and tech finds.Check DealsSlow PC?RecommendedPC slow today? Run a repair scan before it gets worseResolve common Windows issues and optimize system performance.Scan NowOctober DealsAmazon USDeal season is back - check today's better picksAmazon US: current deals, useful picks and tech finds.See Picks×
Skip to content
World desk3 min

How to Rename Files in Python: pathlib, Collisions, and Batch Renames

Use pathlib.Path.rename() for a normal rename, Path.replace() only when overwriting is intended, and shutil.move() when a move may cross filesystems.

What’s actually slowing this PC down?

Pick the symptom - the matching free tool is one click away.

Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.

For a straightforward rename, use pathlib.Path.rename(). Use Path.replace() when overwriting the destination is intentional, or shutil.move() when a move may cross filesystems. The key detail is that a rename’s behavior when the destination already exists can vary by platform.

Rename one file with pathlib

Build a Path for the source and another for the target, then call rename():

from pathlib import Path

source = Path("old_name.txt")
target = Path("new_name.txt")
renamed = source.rename(target)
print(renamed)

Path.rename() accepts a string or path-like target, renames a file or directory, and returns a Path pointing to the target, according to the Python 3.15.0rc3 pathlib documentation.

Relative target paths are resolved from the process’s current working directory, not from the source path’s directory. To keep the destination beside the source, construct it from the source’s parent:

Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.
target = source.with_name("new_name.txt")
source.rename(target)

What happens if the destination already exists?

Do not assume every operating system handles an existing target the same way. The Python 3.15.0rc3 documentation says that Path.rename() silently replaces an existing file on Unix if permitted, but raises FileExistsError on Windows.

Operation Existing destination behavior When to choose it
Path.rename(target) On Unix, an existing file is silently replaced if permitted; on Windows, an existing target raises FileExistsError. (Python 3.15.0rc3 documentation) Ordinary rename when the target is expected not to exist.
Path.replace(target) An existing file or empty directory at the target is unconditionally replaced. (Python 3.15.0rc3 documentation) Use only when replacing the old destination is intended.

replace() is destructive to the existing destination’s contents. If you must avoid overwriting, check for a collision and handle it explicitly rather than relying on the platform’s behavior:

if target.exists():
    raise FileExistsError(f"Destination already exists: {target}")
source.rename(target)

This check is not race-free: another process could create the target after the check. The cited documentation does not promise a portable, race-free no-overwrite pattern for every platform.

Move a file when the filesystem may change

Use shutil.move() if the source and destination may be on different filesystems and its copy-then-remove fallback is suitable. Python 3.14.7 documents that it prefers os.rename() on the same filesystem; if that fails with OSError, it copies using the configured copy function and removes the source. That means a cross-filesystem move is not necessarily one filesystem rename.

Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.
from pathlib import Path
import shutil

source = Path("incoming/report.txt")
target = Path("archive/report.txt")
result = shutil.move(source, target)
print(result)

If the destination is an existing directory (or a symlink to one), shutil.move() places the source inside it; the resulting path must not already exist. It can move directories recursively, and it recreates a symlink at the destination before removing the source symlink. See the Python 3.14.7 shutil documentation.

Rename multiple files safely

For a batch rename, calculate and inspect the complete source-to-target mapping before changing anything. Check for duplicate destinations and for destinations that belong to files which are meant to remain. A preview lets you catch mistakes before the first rename:

from pathlib import Path

folder = Path("files")
renames = [(source, source.with_suffix(".md"))
           for source in folder.glob("*.txt")]

for source, target in renames:
    print(f"{source} -> {target}")

After reviewing the preview, a simple extension change can skip existing targets:

for source, target in renames:
    if target.exists():
        print(f"Skipping {source}: {target} already exists")
        continue
    source.rename(target)

The destination check can still race with another process modifying the directory. Also, a batch is not a transaction: if a later rename fails, earlier changes are not automatically rolled back. Plan how to resume or restore files if partial completion would be a problem.

Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.

When names swap or form a cycle

If one file must take a name currently held by another file—for example, swapping a.txt and b.txt—renaming directly can collide with a file that has not moved yet. Use a two-phase approach: move affected files to unique temporary names first, then move them from those temporary names to their final destinations. Choose temporary names that are not already in use, and retain a record of the mapping so you can recover if either phase stops partway through.

Independent reader supportYour contribution helps us test, update, and keep practical guides available for everyone.Support on Ko-Fi

Equivalent functions in os

For function-oriented or older code, the corresponding operations are os.rename() and os.replace(). The pathlib documentation describes Path.rename() as implemented in terms of os.rename() and sharing its guarantees; prefer the pathlib interface when working with Path objects.

Product prices and availability are accurate as of the date/time indicated and are subject to change. Any price and availability information displayed on Amazon at the time of purchase will apply.

Leave a Reply

Your email address will not be published. Required fields are marked *

Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.

More from the Wire

  1. World desk4 min
    How to Spot an AI Voice Scam Before Sending MoneyDon’t rely on how a caller sounds. Pause, call back through a known number, and verify the emergency with another trusted person before sending money.
  2. Mountain View desk4 min
    Google’s SynthID Detector: How to Check AI-Generated Images, Video and AudioGoogle’s SynthID Detector looks for an embedded watermark in supported images, video and audio. Here is what its results do—and do not—show.
  3. Redmond desk20 min
    How to create a link to File or Folder in Windows 11Windows 11 gives you several ways to point to a file or folder without moving or duplicating it. You can create a desktop shortcut,…
Recommended PC Tool
Recommended PC Tool
PC Slower Than It Used to Be?Free scan - under a minute
Crashes, No Sound, or Screen Glitches?Free driver scan

Two free Windows tools

One Free Minute Could Fix That PC

Before you go - each of these free tools takes about a minute and tackles what quietly slows a Windows PC down.

Special offer. View Outbyte info, uninstall instructions, EULA, and Privacy Policy.