Rename multiple files using Python

To rename files in Python, use the rename() method of the os module. The parameters of the rename() method are the source_address (old name) and the destination_address (new name).

Install and Import the OS module

To install the OS module −

pip install os

To import −

import os

Rename multiple files using rename() method

The rename() method can be easily used to rename multiple files −


import os # Function to rename multiple files def main(): i = 0 path="E:/amit/" for filename in os.listdir(path): my_dest ="new" + 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 main()

The above will rename all the files in a folder “amit”.

Rename specific multiple files

In Python, you can select which multiple files in a folder are to be renamed.

import os filesRename = ['demo_1.txt', 'demo_2.txt', 'demo_3.txt',] folder = r"E:\docs" # Iterate for file in os.listdir(folder): # Checking if the file is present in the list if file in filesRename: oldName = os.path.join(folder, file) n = os.path.splitext(file)[0] b = n + '_new' + '.txt' newName = os.path.join(folder, b) # Rename the file os.rename(oldName, newName) res = os.listdir(folder) print(res)

The above will rename only 3 files in the docs folder.

Updated on: 24-Aug-2023

46K+ Views

Kickstart Your Career

Get certified by completing the course

Get Started