Rename Files in Python

FREE Online Courses: Knowledge Awaits – Click for Free Access!

We often need to rename files on our computers. At those times, we can simply use Python. Python has various functions to rename a file efficiently. When we need to rename multiple files, we can use Python to rename all those files simultaneously to save a lot of development time. We can also use Python to add date stamps to our files. Date stamps help a lot while sorting and managing files. Let us start by learning how to rename a single file in Python.

Rename Files in Python

In Python, we can rename a file using the function rename() available in the OS module. It takes two arguments, the old name and the new name of the file. It has no return value.

Syntax

os.rename(src, dst)

Example of using rename() in Python

import os

print(f"Before Renaming: {os.listdir()}")
os.rename('geeks.txt', 'PythonGeeks.txt')
print(f"After Renaming: {os.listdir()}")

Output

Before Renaming: [‘geeks.txt’]
After Renaming: [‘PythonGeeks.txt’]

If the file is not in the current working directory, then we need to pass the entire path of the file which we want to rename

Example of using rename() in Python

import os

path = "/Users/apple/SchoolFiles/"

print(f"Before Renaming: {os.listdir(path)}")
os.rename(path+'StudentsMarks.txt', path+'Grades.txt')
print(f"After Renaming: {os.listdir(path)}")

Output

Before Renaming: [‘StudentsMarks.txt’]
After Renaming: [‘Grades.txt’]

Python raises FileNotFoundError when it can’t find the passed src file.

Example of using rename() in Python

import os

print(f"Before Renaming: {os.listdir()}")
os.rename('geeks.txt', 'PythonGeeks.txt')
print(f"After Renaming: {os.listdir()}")

Output

Before Renaming: [‘PythonGeeks.txt’]
FileNotFoundError: [Errno 2] No such file or directory: ‘geeks.txt’ -> ‘PythonGeeks.txt’

Renaming Multiple Files in Python

By using a loop and the function listdir() along with rename(), we can rename multiple files at once in Python. listdir() returns a list containing names of all files and directories in the passed directory. We travel through the returned list one by one, renaming each file.

Example on using rename() and listdir() in Python

import os

path = "/Users/apple/School/"
files = os.listdir(path)

print(f"Before Renaming: {files}")
for i in range(len(files)):
   os.rename(path+files[i], f"{path}student{i+1}.txt")
print(f"After Renaming: {os.listdir(path)}")

Output

Before Renaming: [‘SamMarks.txt’, ‘NithyaMarks.txt’, ‘StudentMarks.txt’, ‘WilliamMarks.txt’, ‘JohnMarks.txt’]
After Renaming: [‘student5.txt’, ‘student4.txt’, ‘student3.txt’, ‘student2.txt’, ‘student1.txt’]

Incrementing or Decrementing File Names

If a file name is ‘Student1.txt’, then we can increment it to ‘Student2.txt’ or decrement it to ‘Student0.txt’. To do that we can use the following code.

Example of incrementing file names in Python.

import os

path = "/Users/apple/School/"

to_rename = 5
renamed = 0

print(f"Before Renaming: {os.listdir(path)}")
while renamed < to_rename:
   for file in os.listdir(path):
       if file == f"student{to_rename}.txt":
           os.rename(path+file,f"{path}student{to_rename+1}.txt")
           renamed += 1
           to_rename -= 1

print(f"After Renaming: {os.listdir(path)}")

Output

Before Renaming: [‘AllStudentDetails.txt’, ‘student5.txt’, ‘student4.txt’, ‘student3.txt’, ‘student2.txt’, ‘student1.txt’]
After Renaming: [‘AllStudentDetails.txt’, ‘student6.txt’, ‘student5.txt’, ‘student4.txt’, ‘student3.txt’, ‘student2.txt’]

Renaming a File to Add Date Stamp

By using the datetime module along with the rename() function, we can add a date stamp to a file.

Example of adding date stamp to a file in Python

import os
from datetime import datetime

datestamp = datetime.now().date()


print("Before Renaming:", os.listdir())
os.rename("PythonGeeks.txt", f"PythonGeeks {datestamp}.txt")
print("After Renaming:", os.listdir())

Output

Before Renaming: [‘PythonGeeks.txt’]
After Renaming: [‘PythonGeeks 2021-06-28.txt’]

More function to rename a file in Python

1. os.renames(old, new)

The function is used to rename a file. It needs two arguments, the current name of the file and the new name of the file.

Example on using os.renames() in Python

import os

print("Before renaming:", os.listdir())
os.renames("PythonGeeks.txt", "Geeks.txt")
print("After renaming:", os.listdir())

Output

Before Renaming: [‘PythonGeeks.txt’]
After renaming: [‘Geeks.txt’]

2. os.replace(src, dst)

It is also used to rename a file. It takes two arguments, the current name of the file and the name we want to give to the file.

Example on using os.replace() in Python

import os

print("Before Renaming:", os.listdir())
os.replace("PythonGeeks.txt", "Geeks.txt")
print("After Renaming:", os.listdir())

Output

Before Renaming: [‘PythonGeeks.txt’]
After renaming: [‘Geeks.txt’]

3. shutil.move(src, dst)

The main purpose of this function is to move a file from one directory to another directory. Nonetheless, we still use this function to rename a file by passing the same directory to both src and dst.

Example on using shutil.move() in Python

import os
import shutil

print("Before Renaming:", os.listdir())
shutil.move("Geeks.txt", "PythonGeeks.txt")
print("After Renaming:", os.listdir())

Output

Before Renaming: [‘Geeks.txt’]
After renaming: [‘PythonGeeks.txt’]

Python Interview Questions on How to rename files in Python

Q1. Write a program to rename a file in the current working directory without using the os.renames(old, new) function.

Ans 1. Complete code is as follows:

import os

src = input("File Name: ")
dst = input("New Name: ")
os.rename(src, dst)
print("File Renamed")

Input
File Name: car.png
New Name: bike.png

Output

File Renamed

Q2. Write a program to rename a picture ‘flower.jpg’ to ‘fruit.jpg’ by using the shutil module.

Ans 2. Complete code is as follows:

import os
import shutil

print("Before Renaming:", os.listdir())
shutil.move('flower.jpg', 'fruit.jpg')
print("After Renaming:", os.listdir())

Output

Before Renaming: [‘flower.jpg’]
After renaming: [‘fruit.jpg’]

Q3. Complete the output of the following program.

import os

print(os.listdir())
os.rename("phone.txt", "iphone.txt")
print("File Renamed")

Output

[‘iphone.txt’]

Ans 3. Complete output is as follows:

[‘iphone.txt’]
FileNotFoundError

Q4. Write a program to prefix the names of all files with “New” in the current working directory.

Ans 4. Complete code is as follows:

import os

path = "/Users/apple/PycharmProjects/DataFlair/Articles/School/"
print("Before Renaming:", os.listdir())
for file in os.listdir(path):
   os.rename(path+file, f"{path}New{file}")
print("After Renaming:", os.listdir())

Output

Before Renaming: [‘student2.txt’, ‘student3.txt’, ‘student4.txt’, ‘student5.txt’, ‘student6.txt’, ‘AllStudentDetails.txt’]
After Renaming: [‘Newstudent2.txt’, ‘Newstudent3.txt’, ‘Newstudent4.txt’, ‘Newstudent5.txt’, ‘Newstudent6.txt’, ‘NewAllStudentDetails.txt’]

Q5. Write a program to add the name of the current month to a file ‘monthly bill.jpg’ in the current working directory.

Ans 5. Complete code is as follows:

import os
from datetime import datetime

month = datetime.now().strftime("%B")

print("Before Renaming:", os.listdir())
os.rename('monthly bill.jpg', f'monthly bill {month}.jpg')
print("After Renaming:", os.listdir())

Output

Before Renaming: [‘monthly bill.jpg’]
After Renaming: [‘monthly bill June.jpg’]

Quiz on Rename Files in Python

Conclusion

In this article, from renaming a single file to renaming all files in a directory, we learned all the ways of renaming a file in python. We learned how to add date stamps to our files and how to increment or decrement our files in a directory. Furthermore, if you have any queries, please feel free to share them with us in the comment section.

We work very hard to provide you quality material
Could you take 15 seconds and share your happy experience on Google | Facebook


1 Response

  1. Adam says:

    Hey, I just tried this with os.replace() and all of the files got WIPED OUT instead of being renamed. Just a heads up. (Python 3.9)

Leave a Reply

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