DEV Community

Audrey Kadjar
Audrey Kadjar

Posted on

πŸ“πŸ Automate File Renaming with Python

Renaming files can be a tedious task, especially if you have many. Last time I was sorting through my photos and found myself renaming them one by one, I decided to automate the task πŸ‘©πŸ»β€πŸ”¬


How it Works

  • Input Validation: The script begins by checking if the required arguments are provided via command-line input. If not, it prompts the user to provide the folder path and the new name for the files. The sys module is used to extract the command-line input.

  • File Enumeration: It then lists all the files in the specified folder. The script will iterate through all the eligible files in the folder, renaming them sequentially. The os module is used for file-related operations. A regular expression (file_extension_pattern variable) is defined using the re module. Its role is to match the file extension (eg. .png for a file named image.png).

  • Renaming Process: For each file with an image extension (e.g., JPEG, PNG), the script extracts the file extension using the regular expression pattern, generates a new name, and renames the file accordingly. The new name is formed by concatenating the name, an underscore _, and the count. For example, if the user provides image as the new name and the script processes 3 files, the new names would be: image_1, image_2, image_3. Feel free to adjust this pattern based on your needs.

import os
import sys
import re

if(len(sys.argv) < 3):
    print('Please provide a folder path and a new name.')
    sys.exit(1)

path = sys.argv[1]
name = sys.argv[2]

folder = os.listdir(path)
count = 1
image_extensions = ('jpeg', 'jpg', 'png', 'tiff', 'gif')
base_path = path + '/'
file_extension_pattern = r'\.[^.]+$'

for file in folder:
    if(file.lower().endswith(image_extensions)):
        match = re.search(file_extension_pattern, file)
        file_extension = match.group(0)
        new_name = f"{name}_{count}"
        old_path = base_path + file
        new_path = f"{base_path}{new_name}{file_extension}"
        os.rename(old_path, new_path)
        count+=1
Enter fullscreen mode Exit fullscreen mode

Usage

To utilize this script, follow these steps:

  • Save the script into a file with a .py extension (e.g., rename_files.py).

  • Open a terminal or command prompt and navigate to the directory containing the script.

  • Run the script by providing the folder path and the desired new name as command-line arguments. For example:

python <script> <path> <new_name>
Enter fullscreen mode Exit fullscreen mode
python3 rename_files.py /path/to/folder new_name
Enter fullscreen mode Exit fullscreen mode

That's it! All your files should be automatically renamed ✨

Feel free to reach out if you have any questions! You can also find me on Github, LinkedIn, and Instagram.

Top comments (0)