How to batch rename files in Python

You can automate bulk renaming with a simple Python script. Pass a template into the Python script and allow it to rename all files in a directory using a consistent naming convention.

Once the Python script is ready, you can run it on the command line and the script will rename all the files in a specified directory.

How to iterate through all files in a directory

There are many ways you can batch rename files in Windows, including through Command Prompt or Windows File Explorer.

Another way you can rename files is by using a Python script. If you're not familiar with Python, there are ways you can learn to write better Python code.

To rename all the files in a given directory, you'll need to iterate over the set of files. You can see the full example in this GitHub repo.

1. Create a new folder to store the files you want to rename:

How to batch rename files in Python Picture 1

 

2. Create a new file named batch-rename.py.

3. At the top of the file, import the os module. This will allow you to access the operating system's files and folders:

import os

4. Specify the directory where you have stored the files:

dir_path = "C:UsersSharlDesktopfiles"

You can also use relative paths instead. For example, if your script and file folder are in the same directory, your file path might look like this:

dir_path = "files"

5. Initialize a counter that you will use to append a counter to the end of the filename:

counter = 1

6. Add a for loop to iterate through each file in the directory:

for filename in os.listdir(dir_path):   print("Renaming: " + filename + ".")

7. To test the script, run it on the command line using the python command. Make sure you navigate to the folder location where you stored your script:

cd Desktop python batch-rename.py

How to batch rename files in Python Picture 2

How to rename all files based on a certain pattern

The user will need to enter a template into the script, such as "Financial_Planning". The script will rename all files to the pattern provided and add a count to the end of the filename.

 

1. At the top of the file, import the sys module.

import sys

This will allow you to accept command line arguments. When running the script on the command line, you can enter the pattern you want to use to rename your file.

python batch-rename.py "Financial_Planning"

2. After the input statements, enter the command line arguments. Otherwise, an error message will appear:

commandLineArgs = sys.argv if len(commandLineArgs) > 1:   pattern = commandLineArgs[1] + "_{}" else:   print('Enter a pattern for the new filenames as a command line argument')   sys.exit()

3. Inside the for loop, when iterating through each file, get its file extension:

file_ext = os.path.splitext(filename)[1] 

4. Create a new file name based on the given template. Add a number to the end of the file name and add the file extension again:

new_filename = pattern.format(counter) + file_ext

5. Rename the file with the new filename:

oldFileName = os.path.join(dir_path, filename) newFileName = os.path.join(dir_path, new_filename) os.rename(oldFileName, newFileName)

6. Increment the counter for the next file:

counter += 1

7. After the for loop, the confirmation message will appear:

print("All files renamed.")

8. On a command line, navigate to the directory where you stored your Python script. Use the python command followed by the pattern to rename your file:

How to batch rename files in Python Picture 3

9. Open file explorer and view the renamed files:

How to batch rename files in Python Picture 4

 

Python scripts are a very useful way to automate simple tasks, such as renaming multiple files at once. You can explore other ways to batch rename files on your computer.

4 ★ | 1 Vote

May be interested

  • How to move files by type in Windows with batch filesHow to move files by type in Windows with batch files
    one way to move files in batches as needed, is to use the batch file. with the following command, you can easily move files by type from one folder to another.
  • How to Launch Python Files Using Windows Command PromptHow to Launch Python Files Using Windows Command Prompt
    today's tipsmake will show you how to open python files using the built-in command prompt program on windows computers. in most cases, you will open the file without any problems as long as python is available on your device. if your computer uses an old version of python, or you customized it when installing and did not add the 'python' command to the 'path' variable list, proceed to add python to the 'path' variable list to be able to start. run python files through command prompt.
  • How to Delete a File in Microsoft Windows Using Batch FilesHow to Delete a File in Microsoft Windows Using Batch Files
    this wikihow teaches you how to delete a file on your windows computer by using a batch file. batch files are small files which can run commands via your computer's built-in command prompt program. once you understand how to create a basic...
  • How to Write a Batch FileHow to Write a Batch File
    this wikihow teaches you how to write and save a basic batch file on a windows computer. a batch file contains a series of dos (windows language) commands, and is commonly written to automate frequently performed tasks such as moving...
  • How to batch convert CR2 files to JPG extremely fast using PhotoshopHow to batch convert CR2 files to JPG extremely fast using Photoshop
    if you have 100 cr2 files that need to be converted to jpg at a time, how to do it quickly. this article i will guide you how to batch convert cr2 files to jpg extremely fast in photoshop.
  • Instructions for batch compressing images on Batch Image CompressorInstructions for batch compressing images on Batch Image Compressor
    batch image compressor will help you batch compress images when we can download multiple files at once to reduce capacity.
  • More than 100 Python exercises have solutions (sample code)More than 100 Python exercises have solutions (sample code)
    more than 100 python code examples are shared by guy zhiwehu on github, however, the solution of this series is written on the old python version. following tipsmake.com will be vietnameseized and edited to suit python 3.x to help you learn and practice python.
  • Instructions for creating and using BAT file on WindowsInstructions for creating and using BAT file on Windows
    how to create a simple batch file and some basics about it will be presented in this article. at the same time you will be provided with some resources for learning and writing batch files.
  • How to batch edit photos with Faststone Photo ResizerHow to batch edit photos with Faststone Photo Resizer
    for batch image editing, users can use faststone photo resizer. you can resize, rename, close logo, insert text, ... multiple photos at once.
  • How to copy and rename files in LinuxHow to copy and rename files in Linux
    there are more ways to copy and rename files on linux than just cp and mv. try some commands and other ways suggested below.