Back to articles list Articles
15 minutes read

How to Rename Files Python

How much time do you spend renaming your files? Do you wonder if you could do it more quickly and easily? What if you could rename a huge number of files in the blink of an eye? Python comes with multiple built-in modules and functions to do exactly that. In this article, you will learn how to use many of these modules and functions to rename and move files in Python.

Rename files in Python

Picture by Chris Ried - source: unsplash

Python is a powerful programming language. It is easy to learn due to its straightforward syntax, and it is also versatile. You can do almost everything with it, which explains its widespread popularity.

Even if you are not a professional developer, you can improve your daily productivity with just a few lines of Python code. I abide by the concept of “smart laziness.” If you have to do something more than three times, write a script, and save yourself the hassle!

I find it worthwhile to spend time in the beginning to automate tasks that I will have to perform often to save time in the end. It also helps me to improve my problem-solving skills. One of these tasks is renaming and moving batches of files.

If you don’t know how to do this, or if what I just said sounds like an uphill battle, fear not. At LearnPython.com, we have your back! In this article, I will show you how to move and rename files in Python.

Without further ado, let’s get right to it! To make sure that we are on the same page, I use Windows 10 and Python 3.8.5. It is also a good idea but not compulsory to have some understanding of string manipulation with Python.

Essential Files and Directory Manipulations

To warm ourselves up, let’s perform some essential manipulations using the os module. This will make it easier to understand how to rename files in Python later on.

The os module allows scripts to interact directly with the operating system. It is part of Python’s standard built-in utilities package, and no installation is required.

Let’s write some code to change the directory with os.chdir() and display the current one with os.getcwd().

# import os module
import os

# change directory
os.chdir('c:\\MyDirectory')

# display the current directory
cwd = os.getcwd()

# display directory content
print("current working directory:", cwd)

And here is the output:

Rename files in Python

To run a script, open your Python terminal, and run:

python your_scriptname.py

If you are curious, you can read more about os.chdir() here and os.getcwd() here.

When you explore a new concept, library, or framework, it is always a good idea to read the official documentation.

Rename Files in Python With os.rename()

Now that we have covered some basics, let’s apply the rename method from the os module to rename files in 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 destination.

Let’s run an example. For this tutorial, I collected some stock photos that we are going to rename in Python. Here is my initial photos folder.

Rename files in Python Rename files in Python

First, we are going to rename this beautiful picture of a red sky. As you can see, the file name is not very readable. Let’s rename it red_sky.jpg.

To get started, we can get the file name, type, and location with properties. We will see later that we can use Python to get the file names in our directory. But let’s keep it simple for now.

Rename files in Python

Here is our script:

# import os module
import os

# state file origin and destination as
# os.rename(source, destination)
os.rename(r'C:\py_scripts\photos\abhijeet-gaikwad-bokneofJXeI-unsplash.jpg', r'C:\py_scripts\photos\red_sky.jpg')
print("success")

A Python raw string is a normal string prefixed with the letter r. It treats characters like backslashes as normal characters and not as escape ones. This ensures the correctness of the path so that we can move and rename files in Python on Windows.

Furthermore, the last character cannot be a backslash because it would throw a syntax error.

Let’s run our script and verify the output:

Rename files in Python

Our file has been successfully renamed! You can find more information on os.rename() here as well as in our course on working with files and directories in Python.

Now that we understand the mechanism behind the process of renaming a file in Python, it is important to note that renaming is like moving and vice-versa.

However, if the source and target locations are on different partitions, drives, or devices, os.rename() will not work. If this is the case, use shutil.move() instead.

Move Files in Python With shutil.move()

The shutil module is also part of Python’s standard utility module. Therefore, it does not need to be installed.

Shutil helps to automate the process of copying and removing files and/or directories. With shutil.move(), it is possible to not only rename a file but also change the file directory.

Let’s use the picture that we renamed red_sky.jpg. We will move it to a new folder called awesome and rename the picture awesome_sky.jpg. Are you ready?

This is a screenshot of my photos directory before running our script.

Rename files in Python

Let’s write our script. We need to import the shutil module and state the initial path of the file and its destination. To make the code more readable, I assigned the initial path to a variable called src and the destination path to dst.

Finally, we call the move method from the shutil module.

# import shutil
import shutil

# file source and destination
src=r'C:\py_scripts\photos\red_sky.jpg'
dst=r'C:\py_scripts\photos\awesome\awesome_sky.jpg'

# change file directory and rename file as awesome_sky
shutil.move(src, dst)

As we did earlier, you can now run the script in your python terminal. Here is the final result.

Rename files in Python

You can see that we successfully moved our file to the awesome directory and renamed it awesome_sky.jpg. So, in this example, we learned how to rename and move files in Python.

Awesome, isn’t it?

When you use shutil.move(), a copy of the file is made in the destination path, and the original one is removed.

shutil.move(), contrary to os.rename() will manage different devices, disks, or partitions. In such a case, shutil.move() will first copy the file and then remove it from its original location.

If you do not want to change the file name, you do not need to pass it as a destination parameter. For example: 

shutil.move("my_file.txt", "new_directory")  

You can learn more about shutil.move() here. Also, feel free to check our course on working with files and directories in Python.

Move Files in Python With shutil.copy()

We can also use shutil.copy() to copy a file from one directory to another. Unlike shutil.move(), shutil.copy() will not remove the file from its original location.

In this example, I have a picture called photo_1.jpg that I want to copy to a folder called data1 as seen here:

Rename files in Python

Let’s write a script using shutil.copy() to perform this task.

# import
import shutil

# state source and destination folder
src = r'C:\py_scripts\photos\photo_1.jpg'
dst = r'C:\py_scripts\photos\data1'

# copy src to dst
shutil.copy(src, dst)

And here is the result:

Rename files in Python Rename files in Python

Our photo_1.jpg file is still inside our source directory, and our script created a copy of the same file inside our data1 folder.

shutil.copy() provides us with a way to move files in Python without having to remove them from their original directories. You can find out more about this in the documentation here as well as in our course on working with files and directories in Python.

Rename Files in Python With Pathlib’s Path.rename()

Python pathlib is an object-oriented framework to handle filesystem paths. If you are wondering how to choose between pathlib and the os module, there are a few key differences.

The os module uses a string representation of paths while pathlib creates an object of the directory. The use of pathlib allows for better readability and maintainability of the code, as well as portability to different operating systems.

Let’s rename a file with pathlib. In this example, we will take a new picture and rename it using pathlib. As you can see, our picture name is not very readable at the moment.

Rename files in Python

So, let’s write our script. Pathlib has a clean and intuitive way of building up paths, which we can write as:

Path.cwd() / 'sub directory' / 'filename'

Once the path of our current file is set with the Path class, we then use the rename method with the new path and file name as the argument.

Here’s the code:

# import Path class from pathlib
from pathlib import Path

# define file path that we want to rename
filepath = Path.cwd() / 'photos' / 'diego-ph-5LOhydOtTKU-unsplash.jpg'

# rename file
filepath.rename(Path.cwd() / 'photos' / 'shooting_star.jpg')

See the result below.

Rename files in Python

Our file name is now shooting_star.jpg. You can find more about pathlib’s library to rename files in Python here as well as in our course on working with files and directories in Python.

Batch Rename Files in Python With os.rename() and os.listdir()

We can rename files one by one, but it can become tedious and/or impossible if we have a lot of files. Imagine that you have to prepare a dataset with thousands of pictures to train a computer vision model. It is simply not doable by hand.

Instead, we can batch rename files in Python. Let’s choose a folder with hundreds of pictures to rename using Python to automate this task for us.

Rename files in Python

Again, we will use os.rename(). However, this time, we will need to write a function to loop through the directory and rename the files one after another. Do not forget to add the folder path in the destination.

We will use the os.path.join() method. The first parameter is the path_name, and the second parameter is the file name. This makes the code more readable and cleaner. It also makes it easier to reuse the same code on a different operating system.

Simply modify the path_name variable. In the dst variable, the second parameter is the new file name. I assigned the new file format to a variable called new.

The enumerate() function will return a collection as an object and add a counter as a key of the object.

# import os module
import os

# folder path and destination
path_name = r'C:\py_scripts\photos\data'

# loop through the directory to rename all the files
for count, filename in enumerate(os.listdir(path_name)):
        new ="pic-" + str(count) + '.jpg'  # new file name
        src = os.path.join(path_name, filename)  # file source
        dst = os.path.join(path_name, new)  # file destination
        # rename all the file
        os.rename(src, dst)

Let’s check the results:

Rename files in Python

Our pictures have been renamed successfully. If you want to learn more about os.listdir(), you can check the documentation here as well as our course on working with files and directories in Python.

Batch Rename Files in Python With os.scandir()

We can rename multiple files using os.scandir() instead of os.listdir(). os.scandir() is much faster because it gets an iterator of the os.DirEntry objects.

Let’s write some code. We will use a folder called data1 with multiple pictures. This time, we will rename our files with img as a prefix.

# import os module
import os

# folder path
path = r'C:\py_scripts\photos\data1'

# set counter
count = 1
for f in os.scandir(path):
    if str(f.name).endswith('.jpg'):
        new_file = 'img-' + str(count)+'.jpg'
        src = os.path.join(path, f.name)
        dst = os.path.join(path, new_file)
        os.rename(src, dst)
        count += 1

# close iterator to free some resources
os.scandir(path).close()

Here, contrary to the previous snippet, I added a conditional statement to check if the file has the .jpg extension. In this case, only files with the .jpg file extension will be renamed.

Don’t forget to close the os.scandir() iterator at the end to free some resources and make your code more efficient.

As you can see, we just renamed our data1 folder using os.scandir() method:

Rename files in Python

You can learn more about how to batch rename files in Python with os.scandir() here as well as in our course on working with files and directories in Python.

Batch Rename Files in Python With Pathlib’s Path.iterdir()

We can also batch rename files in Python with pathlib’s Path.iterdir(). Similar to os.scandir(), Path.iterdir() is faster than os.listdir().

This time, I have a folder called data1 with pictures called photo_1.jpg, photo_2.jpg,... I want to rename them as img-1.jpg, img-2.jpg,...

Rename files in Python

Let’s write the script to rename them all.

# import
from pathlib import Path

# set the directory
path = Path.cwd() / 'photos' / 'data1'

# set a counter
counter = 1

# loop through the directory and rename the files
for file in path.iterdir():
    if file.is_file():
        new_file = "img-" + str(counter) + file.suffix
        file.rename(path / new_file)
        counter += 1

And here is the result:

Rename files in Python

It is recommended to use os.scandir() or pathlib’s Path.iterdir() because these methods are better performance-wise, especially in folders with a huge number of files. As a general guideline, it is always good practice to write efficient code because it saves time and resources.

You can read more about how to batch rename files in Python with pathlib’s Path.iterdir() here as well as in our course on working with files and directories in Python.

Batch Rename Files Sequentially in Python

The previous methods are efficient for renaming files, but they do not sort the files to keep them in order. To keep files in order, we can sort them by their last modification time using os.path.getmtime(x). We can then rename the files according to their modification time and add a sequential number to the file name with zfill().

Let’s write some code to sequentially rename our files from a folder named data. We want to rename them photo-01.jpg, photo-02.jpg, etc.

# import os module
import os

# directory path
path_name = r'C:\py_scripts\photos\data'

# Sort list of files based on last modification time in ascending order using list comprehension
name_list = os.listdir(path_name)
full_list = [os.path.join(path_name,i) for i in name_list]
sorted_list = sorted(full_list, key=lambda x: os.path.getmtime(x))

# initiate counter
count = 0

# loop through files and rename
for file in sorted_list:
    # print(file)
    prefix = "photo-"
    counter = str(count).zfill(2)
    new = prefix + counter + '.jpg'  # new file name
    src = os.path.join(path_name, file)  # file source
    dst = os.path.join(path_name, new)  # file destination
    os.rename(src, dst)
    count +=1

Here is the final result:

Rename files in Python

Batch Rename Files in Python With glob.glob() and glob.iglob()

In Python, we can also use the glob module to retrieve files and path names matching a predetermined pattern. Using glob patterns is faster than other methods to match path names in directories.

Similar to the previous modules in this article, it comes built-in with Python, so we do not have to install anything.

We can use glob.glob() or glob.iglob() to retrieve paths recursively from inside the directories and subdirectories. Unlike the glob.glob() method, the glob.iglob() method returns an iterator, which means that not all values are stored in memory, providing more efficiency.

Finally, we can complete the operation with os.rename() to rename our files.

A recursive pattern is a sequence of instructions that loops back to the beginning of itself until it detects that some condition has been satisfied (like reaching the end of what needs to be processed).

Before going further, a word of caution. If you decide to use a recursive pattern, be extra careful. You need to set the base case correctly, otherwise, it can turn into an infinite loop, and the recursive function will keep calling itself forever.

You can probably imagine the damage if your code renamed your files forever, one directory after another... If you want to explore this, set a virtual environment and watch your operating system crumble.

Recursive patterns are powerful but need to be bound by a base case.

In this example, we will work on a folder called data1, which contains a lot of images. We want to rename them all. First, let’s verify that we selected the right files by displaying the file names.

# import glob
import glob

# glob.glob() returns a list of file names
print("Using glob.glob()")
files = glob.glob(r'C:\py_scripts\photos\data1\**\*.jpg', recursive = True)
for file in files:
    print(file)

# glob.iglob() returns an iterator
print("\nUsing glob.iglob()")
for f in glob.iglob('C:\py_scripts\photos\data1\**\*.jpg', recursive = True):
    print(f)

Here is our output using glob.glob():

Rename files in Python

And here is our output using glob.iglob():

Rename files in Python

Our code correctly identified the pictures to be renamed. So, let’s rename our pictures. With glob.glob(), you can use the following code:

# import
import os
import glob

# path
path = r'C:\py_scripts\photos\data1'
path_name = r'C:\py_scripts\photos\data1\**\*.jpg'
# set counter
counter = 1

for f in glob.glob(path_name, recursive = True):
    #print(f)
    new =  "Pic_" + str(counter).zfill(5) + ".jpg"
    dst = os.path.join(path, new)
    os.rename(f, dst)
    counter +=1

The string's zfill() method will rename the pictures with five digits: Pic_00001.jpg, Pic_00002.jpg, etc. Feel free to change the number of digits according to your needs.

Here is the final result:

Rename files in Python

If you prefer glob.iglob(), you can use the following:

# import
import os
import glob

# path
path = r'C:\py_scripts\photos\data1'
path_name = r'C:\py_scripts\photos\data1\**\*.jpg'
# set counter
counter = 1
# glob.iglob() returns an iterator

for f in glob.iglob(path_name, recursive = True):
    #print(f)
    new = "Picture_" + str(counter) + ".jpg"
    dst = os.path.join(path, new)
    os.rename(f, dst)
    counter +=1

Here is the final result:

Rename files in Python

You can find more information about glob.glob() here and glob.iglob() here. Do not forget to check our course as well on working with files and directories in Python.

Batch Rename Files in Python With os.walk(cwd)

Let’s make it a bit more difficult. We can also get files from nested directories, rename them, and move them to a single directory. Let’s do this with os.walk(cwd).

os.walk() generates the file names in a directory tree by walking the tree either top-down or bottom-up. Then, it yields a tuple of three elements (dir_path, dir_names, file_names).

This time, I have pictures in 2 different folders called data1 and data2. I want to rename them and move them all to a different folder called all.

Here is my data1 folder:

Rename files in Python

And here is my data2 folder:

Rename files in Python

Let’s write some code:

# import
import os

# define current working directory
cwd = 'C:\py_scripts\photos'
count = 1
for dir_path, dir_names, file_names in os.walk(cwd):
    for f in file_names:
        if f.endswith('.jpg'):
            new = 'pic_' + str(count) + '.jpg'
            dest_dir = os.path.join(cwd,'all')
            # create new directory if does not exist
            if not os.path.isdir(dest_dir):
                os.mkdir(dest_dir)
            os.rename(os.path.join(dir_path, f), os.path.join(dest_dir, new))
            count += 1

Here is the result:

Rename files in Python

So, our data1 and data2 folders are now empty, and our pictures have been renamed and moved to the all folder.

You can learn more about os.walk() here. You can also check our course on working with files and directories in Python.

Closing Thoughts

We covered a lot of ground in this article! We learned multiple ways to:

  • Rename files in Python
  • Move files in Python
  • Batch rename files in Python
  • Batch move files in Python

Do not hesitate to reuse the code above to help you get started. Play with the code and start automating some of your recurring tasks with Python.

To bring your Python programming skills to the next level, don’t forget to check our Python programming track and LearnPython.com!