Python Rename File and Directory using os.rename()

โšก Smart Summary

Python renames files and directories with os.rename(). Here you will learn os.rename(), os.renames(), shutil.move(), and pathlib Path.rename(), plus how to rename a directory and batch-rename multiple files with clear examples.

  • โœ๏ธ os.rename(): os.rename(src, dst) renames a file or directory; the source must exist.
  • ๐Ÿ—‚๏ธ os.renames(): os.renames() also creates missing destination folders automatically.
  • ๐Ÿšš shutil.move(): shutil.move() renames and can move files across file systems.
  • ๐Ÿ pathlib: Path.rename() renames files the object-oriented way (Python 3.4+).
  • ๐Ÿค– AI help: AI tools like Copilot generate rename and batch-rename code instantly.

Python Rename File os.rename()

Python Rename File

Python rename() file is a method used to rename a file or a directory in Python programming. The Python rename() file method can be declared by passing two arguments named src (Source) and dst (Destination).

Syntax

This is the syntax for os.rename() method

os.rename(src, dst)

Parameters

src: Source is the name of the file or directory. It should must already exist.

dst: Destination is the new name of the file or directory you want to change.

Example:

import os  
os.rename('guru99.txt','career.guru99.txt')

Let’s look at example in detail

You can rename the original file, we have changed the file name from “Guru99.txt” to “Career.guru99.txt.”

Python Rename File

  • To rename “guru99.txt” file, we going to use “rename function” in the OS module
  • So when the code is executed, you can observe that a new file “career.guru99.txt” is created on the right side of the panel, which we renamed for our original file.

Here is the complete code

import os
import shutil
from os import path

def main():
	# make a duplicate of an existing file
    if path.exists("guru99.txt"):
	# get the path to the file in the current directory
        src = path.realpath("guru99.txt");
		
	# rename the original file
        os.rename('guru99.txt','career.guru99.txt') 
		
if __name__ == "__main__":
    main()

How to Rename a Directory in Python

The os.rename() method also renames directories, not just files. Pass the current folder name as the source and the new name as the destination.

import os
os.rename("old_directory", "new_directory")

If the source directory does not exist, Python raises a FileNotFoundError, so it is good practice to check the path first.

Rename a File Using os.renames()

The os.renames() method renames a file and automatically creates any missing intermediate directories in the destination path. It also removes empty directories left behind in the source path.

import os
os.renames("guru99.txt", "archive/2024/career.txt")

Here the folders archive and 2024 are created automatically if they do not already exist.

Rename a File Using shutil.move()

The shutil.move() function moves a file to a new location, which effectively renames it when the destination is the same directory.

import shutil
shutil.move("guru99.txt", "career.guru99.txt")

Unlike os.rename(), shutil.move() can also move a file across different file systems or drives.

Rename a File Using the pathlib Module

In Python 3.4 and later, the pathlib module offers an object-oriented Path.rename() method for renaming files.

from pathlib import Path

file = Path("guru99.txt")
file.rename("career.guru99.txt")

The rename() method returns a new Path object that points to the renamed file.

How to Rename Multiple Files in Python

To rename many files at once, loop over the files in a directory with os.listdir() and call os.rename() for each one. The example below adds a numbered prefix to every file.

import os

folder = "myfiles"
for count, filename in enumerate(os.listdir(folder)):
    new_name = f"file_{count}.txt"
    os.rename(os.path.join(folder, filename), os.path.join(folder, new_name))

Using os.path.join() keeps the code working correctly on any operating system.

FAQs

Import os and call os.rename(src, dst), passing the current file name and the new name. The source file must already exist, or Python raises FileNotFoundError.

os.rename() renames a single file or directory, while os.renames() also creates any missing intermediate directories and removes empty source folders after the move.

Yes. shutil.move(src, dst) renames a file when the destination is the same folder, and can also move files across different file systems, unlike os.rename().

Use os.rename(‘old_dir’, ‘new_dir’). The same os.rename() function works for both files and directories, as long as the source directory exists.

Loop over os.listdir(folder) and call os.rename() for each file. Use os.path.join() to build full paths so the code works on any operating system.

AI assistants like GitHub Copilot autocomplete os.rename() and pathlib calls, and generate batch-rename loops from a comment describing the naming pattern you want.

Yes. AI-powered tools can automate writing batch-rename scripts, apply patterns like numbering or date prefixes, and add error handling for missing or duplicate names.

On Windows, os.rename() raises FileExistsError if the destination exists. On Unix, it silently overwrites. Check with os.path.exists() first to avoid losing data.

Summarize this post with: