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 :



filter_none

edit
close

play_arrow

link
brightness_4
code

# Python program to rename all file
# names in your directory 
import os
  
os.chdir('D://Geeksforgeeks')
print(os.getcwd())
COUNT = 1
  
# Function to increment count 
# to make the files sorted.
def increment():
    global COUNT
    COUNT = COUNT + 1
  
  
for f in os.listdir():
    f_name, f_ext = os.path.splitext(f)
    f_name = "geek" + str(COUNT)
    increment()
  
    new_name = '{} {}'.format(f_name, f_ext)
    os.rename(f, new_name)

chevron_right


Output:



My Personal Notes arrow_drop_up

Competitive Programmer, Full Stack Developer, Technical Content Writer, Machine Learner

If you like GeeksforGeeks and would like to contribute, you can also write an article using contribute.geeksforgeeks.org or mail your article to contribute@geeksforgeeks.org. See your article appearing on the GeeksforGeeks main page and help other Geeks.

Please Improve this article if you find anything incorrect by clicking on the "Improve Article" button below.



Improved By : Shivam_k