Renaming Files in Python

In this TechVidvan article, we will look at how to rename files in Python using the os and shutil modules. We’ll go over how to rename single files as well as how to rename multiple files in a directory. Furthermore, we will discuss best practices for working with files and directories in Python and provide examples to demonstrate each method.

Whether you’re a beginner or a seasoned Python developer, this article will help you work with files in your Python projects.

Using the os.rename() method to rename a file in Python

In Python, the os.rename() method is used to rename a file or directory. It accepts two arguments: the current and new names of the file or directory. An example of how to use os.rename() to rename a file called “old file.txt” to “new file.txt” is as follows:

import os
os.rename('old_file.txt', 'new_file.txt')

It is important to note that if the file or directory you are attempting to rename does not exist, the os.rename() method will throw a FileNotFoundError. Also, if the destination file exists already, it will be overwritten.

It’s also worth noting that the os.rename() method is platform dependent and may not work as expected on different platforms. For example, if the file or directory you’re trying to rename is already in use or you don’t have the necessary permissions, it will raise a PermissionError.

Renaming Multiple Files in Python

There are several ways to rename multiple files in Python. One way is to use a loop to iterate through a list of files and call the os.rename() method on each one. Here is an example of how to rename multiple files in a directory:

import os
# list of files to be renamed
files_to_rename = ['file1.txt', 'file2.txt', 'file3.txt']
# new names for the files
new_names = ['new_file1.txt', 'new_file2.txt', 'new_file3.txt']
# rename the files
for i in range(len(files_to_rename)):
os.rename(files_to_rename[i], new_names[i])
print('Files renamed successfully')

This code will not produce any output, other than the print statement that says “Files renamed successfully” if all the files are renamed successfully.

In this example, we first defined two lists: one for the current names of the files, and one for the new names. We then use a for loop to iterate through the files_to_rename list and call the os.rename() method for each file, passing the current name and the new name as arguments.

Another way to rename multiple files is to use the os.scandir() method and os.rename() method, it will scan the directory and return an iterator over the files in the directory.

import os
# path of the directory where files are located
dir_path = 'path/to/directory'
# new names for the files
new_names = ['new_file1.txt', 'new_file2.txt', 'new_file3.txt']
i = 0
for file in os.scandir(dir_path):
if file.name.endswith('.txt'):
os.rename(file, os.path.join(dir_path, new_names[i]))
i += 1
print('Files renamed successfully')

The output will not be displayed if the code runs successfully because the print statement is inside the loop and will be executed for every file that matches the conditions.

In this example, os.scandir() method is used to scan the directory where files are located. The os.rename() method is then used to rename the files with the new names. In the example above, we are renaming only the files with the ‘.txt’ extension, but you can change the extension as per your requirement.

Please keep in mind that in both the above examples, if the destination file already exists, it will be overwritten. Also, it’s a good idea to include error handling in your code, in case the os.rename() method raises an exception.

Renaming only the Extension of the file in Python

To rename only the extension of a file in Python, you can use the os.path module to manipulate the file name and extract the base name and extension separately. Here is an example of how to change the extension of a file from “.txt” to “.csv”:

import os
# current file name
file_name = 'example.txt'
# new extension
new_extension = '.csv'
# extract base name and extension
base_name, extension = os.path.splitext(file_name)
# create new file name
new_file_name = base_name + new_extension
# rename the file
os.rename(file_name, new_file_name)
print('File extension changed successfully')

Output:

File extension changed successfully

In this example, we first define the current file name and the new extension. We then use the os.path.splitext() method to extract the base name and extension of the file. We then create the new file name by concatenating the base name and the new extension. Finally, we use the os.rename() method to rename the file.

You can also use string operations and other methods to extract the base name and new extension as well and then use os.rename() method.

import os
# current file name
file_name = 'example.txt'
# new extension
new_extension = '.csv'
# extract base name and extension
base_name = file_name.split('.')[0]
# create a new file name
new_file_name = base_name + new_extension
# rename the file
os.rename(file_name, new_file_name)
print('File extension changed successfully')

Please keep in mind that in both of the above examples, if the destination file already exists, it will be overwritten. Also, it’s a good idea to include error handling in your code, in case the os.rename() method raises an exception.

Output:

File extension changed successfully

Conclusion

Renaming files in Python is a simple task that can be accomplished using the built-in os and os.path modules. The os.rename() method can be used to rename a single file or directory, while a loop and the os.scandir() method can be used to rename multiple files in a directory. Additionally, the os.path.splitext() method can be used to extract the base name and extension of a file, allowing you to change only the extension of a file.

It’s important for us to keep in mind that the os.rename() method may raise an exception, such as FileNotFoundError or PermissionError, if the file or directory which we are trying to rename does not exist or if we don’t have the necessary permissions. It’s also important to be aware that the os.rename() method is platform dependent.

In this article, we have covered different ways by which we can rename files and directories in Python along with examples. One should now have a good understanding of how one should work with files in Python and be able to use this knowledge in making our own projects.