Wednesday, July 3, 2024
HomeLanguagesPythonRename all file names in your directory using Python

Rename all file names in your directory using Python

Given multiple files in a directory having different names, the task is to rename all those files in sorted order. 
We can use OS module in order to do this operation. The OS module in Python provides functions for interacting with the operating system and provides a portable way of using operating system-dependent functionality. We can go to the current working directory using os.getcwd() method and rename the files with os.rame() method. 
 

Below is the Python implementation : 

Python3




# Python program to rename all file
# names in your directory
import os
 
os.chdir('D:\\GeeksforLazyroar')
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: 
 

 

Dominic Rubhabha Wardslaus
Dominic Rubhabha Wardslaushttps://neveropen.dev
infosec,malicious & dos attacks generator, boot rom exploit philanthropist , wild hacker , game developer,
RELATED ARTICLES

LEAVE A REPLY

Please enter your comment!
Please enter your name here

Most Popular

Recent Comments