How to Rename a file in Python?

The os module in Python comes in handy in performing any file operations such as reading a file, writing into a file etc.. The rename() method is used to rename a file or directory in Python.

Python Rename File

Python rename() function can rename any file type extension or folder in Python. 

Syntax

os.rename(src, dst)

Parameters

  • src: src is the source file name that needs to be renamed. If the function cannot find the file or is inaccessible, Python will raise an OSError
  • dst: dst is the destination file name which is the new name of the file or directory

Note: If the dst already exists, then the FileExistsError will be thrown in Windows, and in the case of UNIX, an OSError will be thrown.

Example to rename a file in Python

# Import os module
import os

# file name old and new. This can be even absolute path
old_file_name = "python.txt"
new_file_name = "python_renamed.txt"

# use rename function to rename the file or directory
os.rename(old_file_name, new_file_name)

print("Successfully renamed a file !")

Output

Successfully renamed a file !

Python Rename Multiple Files

There are times where you may need to rename multiple files in the same directory recursive. Let’s say some automated batch job creates a new file with the same name, and you still need to back up the old files by just renaming them as old_filename then, you can use rename() method to perform batch rename.

Example to Rename Multiple Files in Python

The code is straightforward. We can use the os.listdir() method in a loop that can get all the files, iterates each file inside the loop, and use the rename() function to rename the file.  

# Import os module
import os

# Batch rename all the file in the specified directory
for file in os.listdir("C:/Projects/Tryouts"):
	os.rename(file, f"C:/Projects/Tryouts/old_{file}")

Output

old_test.txt
old_python.text
old_student.csv

Note: You can give the src and dst in the absolute path or relative name depending on where the file is placed, and the code is running. In the example, we have used both absolute and relative file names.