Python rename all file names in a directory

Rename All Filenames in a Directory in Python

Given multiple files in a directory with different names, the task is to rename all of them in sorted order.

We can use the os module to accomplish this. The os module in Python provides functions for interacting with the operating system and provides a portable way to use operating system-related functionality. We can use the os.getcwd() method to change to the current working directory and the os.rename() method to rename files.

Code implementation

# Python program to rename all file
# names in your directory
import os
 
os.chdir('D:Geeksforgeeks')
print(os.getcwd())
 
for count, f in enumerate(os.listdir()):
f_name, f_ext = os.path.splitext(f)
f_name = "geek" + str(count)
 
new_name = f'{f_name}{f_ext}'
    os.rename(f, new_name)

Output:

Python renames all file names in a directory

Leave a Reply

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