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.

Leave a Reply

Your email address will not be published.

Sign Up for Our Newsletters

Get notified of the best deals on our WordPress themes.

You May Also Like
Python String Rjust().Png

Python String rjust()

Table of Contents Hide rjust() Syntaxrjust() Parametersrjust() Return valueExample 1 : Python program to right justify a stringExample 2: rjust() Method With * fillcharExample 3: Returns original string if the…
View Post
Calculate Euclidean Distance In Python

Calculate Euclidean Distance in Python

Table of Contents Hide How to Calculate Euclidean Distance in Python?Method 1: Using linalg.norm() Method in NumPyMethod 2: Using dot() and sqrt() methodsMethod 3: Using square() and sum() methodsMethod 4:…
View Post
Python List Insert()

Python List insert()

Table of Contents Hide Syntax of List insert() insert() ParametersReturn Value from List insert()Example 1: Inserting an Element to the ListExample 2: Inserting an element at the start and end of…
View Post
How To Check If A File Exists In Python

How to check if a file exists in Python?

Table of Contents Hide Python check if a file exists using OS ModuleUsing os.path.exists()Using os.path.isfile()Using os.path.isdir()Using pathlib.Path.exists() When you perform a file operation such as reading from a file or…
View Post