How to Batch Rename Files in Python?


If you have a lot of files that you need to rename, it can be tedious to do it one by one. Python has a built-in module called “os” that can help us batch rename files. In this blog post, we will go over how to use this module to bulk rename files.

When you change name file, you can add a string or serial number before and after the file name in Python.

Note: When you process renaming the file name, you should save the original file separately so that you don’t have to worry if it fails.

Rename with os.rename()

Now that we’ve gone over some basics, let’s use the os module’s rename() method to change the name of a file in Python.

os.rename(src, dst, *, src_dir_fd=None, dst_dir_fd=None) #Rename file or directory from <strong>src </strong>to <strong>dst</strong>.
Code language: Python (python)

To rename a single file, we need to enter the file’s current name with its current location and its new name with its new destination.

# import os module import os # state file origin and destination as # os.rename(source, destination) os.rename(r'C:\myphotos\old_name.jpg', r'C:\myphotos\new_name.jpg') print("success")
Code language: PHP (php)

old_name.jpg file will be renamed to new_name.jpg file.

If a file already exists, you can rename it.

import os old_name = r"C:\myphotos\old_name.jpg" new_name = r"C:\myphotos\new_name.jpg" try: os.rename(old_name, new_name) except FileExistsError: print("File already Exists") print("Removing existing file") # skip the below code # if you don't' want to forcefully rename os.remove(new_name) # rename it os.rename(old_name, new_name) print('Done renaming a file')
Code language: Python (python)

Rename multiple files using Python

Example 1: rename multiple files

# importing os module import os # Function to rename multiple files def main(): folder = "my_mages" for count, filename in enumerate(os.listdir(folder)): new_image_file = f"Hostel {str(count)}.jpg" src =f"{folder}/{filename}" # foldername/filename, if .py file is outside folder dst =f"{folder}/{new_image_file}" # rename() function will # rename all the files os.rename(src, dst) # Driver Code if __name__ == '__main__': # Calling main() function main()
Code language: Python (python)

Example 2:

import os folder = r'E:\my_mages\\' count = 1 # count increase by 1 in each iteration # iterate all files from a directory for file_name in os.listdir(folder): # Construct old file name source = folder + file_name # Adding the count to the new file name and extension destination = folder + "flower_" + str(count) + ".jpg" # Renaming the file os.rename(source, destination) count += 1 print('All Files Renamed') print('New Names are') # verify the result res = os.listdir(folder) print(res)
Code language: Python (python)

Example 3: Renaming files with a timestamp

import os from datetime import datetime # adding date-time to the file name current_timestamp = datetime.today().strftime('%d-%b-%Y') old_name = r"D:\files\old_flower.txt" new_name = r"D:\files\new_flower" + current_timestamp + ".txt" os.rename(old_name, new_name)
Code language: PHP (php)

Example 4: Renaming files with a Pattern

import glob import os path = r"E:\flowers\\" # search text files starting with the word "sales" pattern = path + "rose" + "*.png" # List of the files that match the pattern result = glob.glob(pattern) # Iterating the list with the count count = 1 for file_name in result: old_name = file_name new_name = path + 'Orchid_' + str(count) + ".png" os.rename(old_name, new_name) count = count + 1 # printing all revenue txt files res = glob.glob(path + "Orchid" + "*.png") for name in res: print(name)
Code language: PHP (php)

The glob module follows the rules used by Unix shells to find all pathnames matching a given pattern.

For example, glob.glob(‘./*’) you can get a list of file names and directory names in the current directory with . The argument can be an absolute path or a relative path.

In this example,

import glob print( glob.glob( './mydir/*' )) # => ['./mydir/rose_a.jpg', './mydir/rose_b.jpg', './mydir/rose_c.jpg', ' ./mydir/rose_d.jpg', './mydir/rose_e.jpg']
Code language: Python (python)

You can use the following pattern matches:

  • *: matches anything
  • ?: matches any single character
  • [abc]: matches a single character a, b, or c
  • [!abc]: matches a single character other than a, b, c

Example 5: add a string/sequence number to the front of a file

import os import glob path = "./mydir" files = glob.glob(path + '/*') for f in files : os . rename (f, os.path.join(path, 'img_' + os.path.basename(f))) # img_rose_a.jpg # img_rose_b.jpg # img_rose_c.jpg for i, f in enumerate(files, 1): os.rename(f, os.path.join(path, '{0:03d}'.format(i) + '_' + os.path.basename(f))) # 001_rose_a.jpg # 002_rose_b.jpg # 003_rose_c.jpg
Code language: Python (python)

Example 6: add a string/sequence number to the end of a file

import os import glob files = glob.glob('./mydir/*') for f in files : ftitle, fext = os.path.splitext(f) os.rename(f, ftitle + '_img' + fext) # rose_a_img.jpg # rose_b_img.jpg # rose_c_img.jpg for i, f in enumerate(files): ftitle , fext = os.path.splitext(f) os.rename(f, ftitle + '_' + '{0:03d}'.format(i) + fext) # rose_a_001.jpg # rose_b_002.jpg # rose_c_003.jpg
Code language: Python (python)

Example 7: Renaming the Extension of the Files

Now, using the replace() method of an str class to replace an existing extension with a new extension in the file name

import os folder = r"E:\flowers\\" # Listing the files of a folder print('Before rename') files = os.listdir(folder) print(files) # rename each file one by one for file_name in files: # construct full file path old_name = os.path.join(folder, file_name) # Changing the extension from txt to pdf new_name = old_name.replace('.jpg', '.txt') os.rename(old_name, new_name) # print new names print('After rename') print(os.listdir(folder))
Code language: Python (python)

Example 8: Renaming and then moving a file to a new location

import os # Old and new folder location old_folder = r"D:\folder\\" new_folder = r"E:\New_folder\\" # Old and new file names old_name = old_folder + "abc.txt" new_name = new_folder + "abc.txt" # Moving the file to the another location os.rename(old_name, new_name)
Code language: Python (python)

Example 9: Renaming only a list of files in a folder

import os files_to_rename = ['flower_1.txt', 'flower_5.txt'] folder = r"E:\flowers\\" # Iterate through the folder for file in os.listdir(folder): # Checking if the file is present in the list if file in files_to_rename: # construct current name using file name and path old_name = os.path.join(folder, file) # get file name without extension only_name = os.path.splitext(file)[0] # Adding the new name with extension new_base = only_name + '_new' + '.jpg' # construct full file path new_name = os.path.join(folder, new_base) # Renaming the file os.rename(old_name, new_name) # verify the result res = os.listdir(folder) print(res)
Code language: Python (python)

Andy Avery

I really enjoy helping people with their tech problems to make life easier, ​and that’s what I’ve been doing professionally for the past decade.

Recent Posts