Rename multiple files using Python

PythonProgrammingServer Side Programming

rename() method is used to rename a file or directory in Python3. The rename() method is a part of the os module.

Syntax for os.rename()

os.rename(src, dst)

The first argument is src which is source address of file to be renamed and second argument dstwhich is the destination with the new name.

Let's take any directory which has one image folder. Here we have this image folder.



Example code

import os
# Function to rename multiple files
def main():
   i = 0
   path="C:/Users/TP/Desktop/sample/Travel/west bengal/bishnupur/"
   for filename in os.listdir(path):
      my_dest ="soul" + str(i) + ".jpg"
      my_source =path + filename
      my_dest =path + my_dest
      # rename() function will
      # rename all the files
      os.rename(my_source, my_dest)
      i += 1
# Driver Code
if __name__ == '__main__':
   # Calling main() function


Rename Output
Updated on 30-Jul-2019 22:30:23