HOWTO · Python

How to Rename a File in Python

This article guides you on how to rename a file in Python, covering methods using the os and pathlib modules. You'll learn about exception handling and best practices to ensure smooth file management. Whether you're a beginner or an experienced programmer, this comprehensive guide will enhance your file manipulation skills in Python.

On this page

To rename one file in Python, call os.rename(), pathlib.Path.rename(), or shutil.move() with the source and destination paths. Use os.rename() or Path.rename() for a filesystem rename; choose shutil.move() when the destination may be on another filesystem. The examples below create their own temporary files, so they do not depend on a particular working directory or modify a project file.

Rename a file with os.rename()

os.rename(source, destination) changes the source path to the destination path. Construct paths with pathlib so they are joined using the current operating system’s path rules. This example creates a file inside a temporary directory and renames it there:

Run this example:

import os
from pathlib import Path
from tempfile import TemporaryDirectory

with TemporaryDirectory() as folder:
    source = Path(folder) / "draft.txt"
    destination = Path(folder) / "final.txt"
    source.write_text("Report", encoding="utf-8")
    os.rename(source, destination)
    print(destination.name, destination.read_text(encoding="utf-8"))

The call returns None when it succeeds. Relative paths are interpreted from the process’s current working directory, which can differ from the directory containing your script. Building paths from a known directory avoids that ambiguity.

Rename a file with pathlib.Path.rename()

Path.rename() performs the same kind of rename while keeping source and destination as path objects. with_name() makes a sibling path with a new filename; it does not rename the file by itself.

from pathlib import Path
from tempfile import TemporaryDirectory

with TemporaryDirectory() as folder:
    source = Path(folder) / "draft.txt"
    source.write_text("Report", encoding="utf-8")
    destination = source.with_name("final.txt")
    renamed_path = source.rename(destination)
    print(renamed_path.name, renamed_path.read_text(encoding="utf-8"))

The returned value is a Path for the new location. Use this method when your code already represents paths with Path; it has the same operating-system rename constraints as os.rename().

Rename or move a file with shutil.move()

shutil.move(source, destination) accepts path-like values and returns the destination path as a string. If a same-filesystem rename is possible, it uses that operation. If moving across filesystems, it can copy the file and then remove the source, so it is not necessarily an atomic rename.

import shutil
from pathlib import Path
from tempfile import TemporaryDirectory

with TemporaryDirectory() as folder:
    source = Path(folder) / "draft.txt"
    destination = Path(folder) / "final.txt"
    source.write_text("Report", encoding="utf-8")
    moved_to = shutil.move(source, destination)
    print(Path(moved_to).name, Path(moved_to).read_text(encoding="utf-8"))

When the destination names an existing directory, shutil.move() places the source inside that directory using its basename. Otherwise it treats the destination as the new path. Check the destination shape carefully when a directory and a filename could be confused.

Handle paths, missing files, and existing destinations

The source must exist and the destination’s parent directory must be available. A missing source or parent commonly raises FileNotFoundError; permissions, open-file restrictions, and other filesystem conditions can raise PermissionError or another OSError. Catch the narrow errors your application can recover from, and let unexpected failures remain visible. Do not catch every exception just to print a success-like message.

The behavior when a destination file already exists is platform-dependent. On some systems, a rename may replace an existing file; on others it fails. Path.rename() follows the same underlying rule. shutil.move() also relies on rename when possible and uses copy-and-remove behavior across filesystems, so do not assume one overwrite result for every platform and filesystem. For a no-overwrite workflow, check that the destination is absent before moving, while recognizing that another process could create it between the check and operation. For stronger guarantees, use an operating-system-specific exclusive operation appropriate to your application.

Choose the right method

For a simple rename on one filesystem, use Path.rename() if the rest of your code uses pathlib, or os.rename() if it already uses string paths or the os module. Both return None. Choose shutil.move() when a move may cross filesystem boundaries or when its directory-destination behavior is useful; it returns the resulting destination path. All three require a valid source, and none makes a multi-step copy-and-remove move atomic. Keep source and destination paths explicit, decide how your application should handle collisions, and test filesystem-sensitive behavior on the platforms you support.