Renaming files is an essential task for system administrators when managing and organizing file systems. Python offers built-in functions to simplify the process of renaming files.
To rename a file in Python, you can use the os.rename() function. You must first import the os module, then use the os.rename() method by providing the current filename (or path) as the first argument and the new filename (or path) as the second argument. You can also use the shutil and glob modules to rename files in Python.
In this article, we will discuss how to rename a file in Python. We will cover the syntax, use cases, and provide examples to demonstrate their effectiveness.
So, let’s get started!
2 Ways to Rename a Single File in Python
When renaming a single file in Python, you can use the following 2 methods:
- Using the os.rename() function
- Using the shutil module
1) How to Rename a Single File Using The os.rename() Function
The os module provides several tools for working with files and interacting with the operating system. One of these tools is the os.rename() function.
os.rename() function is used to rename a single file. It takes two main parameters: the source path (src) and the destination path (dst).
The source path is the current file path, while the destination path is the new file path.
The syntax of os.rename is:
import os
os.rename(src, dst, src_dir_fd=None, dst_dir_fd=None)
Here’s a brief explanation of the parameters:
- src: The current file path and filename. (e.g., ‘old_file.txt’)
- dst: The new file path and filename. (e.g., ‘new_file.txt’)
- src_dir_fd [Optional]: The source file directory.
- dst_dir_fd [Optional]: The destination file directory.
If the destination file already exists, Python will raise a FileExistsError.
Also, if the source file doesn’t exist, it will raise a FileNotFoundError.
Example of Renaming a Single File Using The os.rename() Function
The following code snippet demonstrates renaming a file using the os.rename() function:
import os
src = 'old_file.txt'
dst = 'new_file.txt'
#Rename the file
os.rename(src, dst)
The demonstration is shown below:
In this example, the file named old_file.txt will be renamed to new_file.txt.
2) How to Rename a Single File Using the Shutil Module
The shutil module provides the move() function that can also be used for renaming files.
This method is useful when you need additional control over file renaming, such as renaming files across different directories or preserving metadata.
Here’s an example of using shutil.move():
import shutil
src = 'path/to/old_file.txt'
dst = 'path/to/new_file.txt'
shutil.move(src, dst)
The shutil.move() function takes two arguments:
- src: The source file path (the existing file to be renamed).
- dst: The destination file path (the new filename for the file).
Just like the os.rename() function, it changes the name of the file. However, the shutil.move() function also returns the new name or the directory of the file.
For example, let’s rename the file with today’s date:
import shutil
from datetime import date
today = str(date.today())
src = 'old_file.txt'
dst = 'new_path/new_file'+ today +'.txt'
ret = shutil.move(src, dst)
print(ret)
The output of the above code will be:
new_path/new_file2023-08-03.txt
2 Ways to Rename Multiple Files with Python
When working with files in Python, you might need to rename multiple files in a particular folder.
You can do this with the following 2 methods:
- Using the os.listdir() function with a for loop
- Using the glob module
1) How to Rename Multiple Files Using The os.listdir() Function With a For Loop
The os.listdir() function returns a list of file names (both file and directory names) in the specified directory. If no path is specified, it will list the contents of the current working directory.
For example, let’s say we have a folder filled with images:
import os
# List all files in the current working directory
files = os.listdir()
print("Files in the current directory:", files)
Output:
Files in the current directory: ['bonsai-rock-sunset.jpg', 'download (1).jfif', 'download.jfif', 'Tsunami_by_hokusai_19th_century.jpg', 'wallpaperflare.com_wallpaper.jpg']
Now, I want to add some order and rename them as Picture_1, Picture_2, etc. We do this with the listdir() function and the rename() function with a for loop.
Here’s how:
import os
# List all files in the current working directory
files = os.listdir()
i = 1
for file in files:
os.rename(file, f'Picture {i}')
i+= 1
The output is shown below:
We can see that the files are now renamed in order. However, this might not be very precise if you’re only looking to rename certain files.
Let’s look at how you can achieve that.
2) How to Rename Multiple Files Using The Glob Module
The glob module can be used to find all the files in a folder matching a pattern.
This is useful when you want to rename a specific set of files.
Let’s say you have several .jpg files in the same folder that begin with the string “year” and you want to rename them to start with “new_year”.
Here’s how you can do it:
import os
import glob
# Find all files with names starting with "year" and ending with ".jpg"
files = glob.glob('year*.jpg')
# Loop through each file and rename them
for file in files:
# Split the file name at the '_' character
parts = file.split('_')
# Create a new file name using the parts and the desired prefix
new_name = f'new_year_{parts[1]}'
# Rename the file using os.rename()
os.rename(file, new_name)
In the above sample code, we’ve used glob.glob() to find all the .png files that begin with the string “year”. Then, we loop over each file using a for loop.
Inside the loops, we split the file name and create a new name with the desired prefix. Finally, we use the os.rename() function to rename the files.
Remember to always handle exceptions and edge cases when implementing such code, as file operations can be prone to errors such as permission issues or non-existent files.
How to Handle Errors and Exceptions
When renaming files in Python using the os.rename() function, one common error that might occur is the OSError.
This error usually signifies an issue in manipulating files or directories in the operating system.
Some common reasons for OSError include file not found, permission issues, or trying to rename a file that is in use by another process.
To handle these errors effectively, you can use Python’s exception handling mechanism with try and except blocks.
Surround the code that may raise an OSError with a try block, and then catch the exception using an except block followed by the specific error type you want to handle.
In the case of file renaming, an OSError can be caught and handled as follows:
import os
try:
os.rename("old_filename.txt", "new_filename.txt")
except OSError as e:
print(f"Error: {e}")
Output:
Error: [WinError 2] The system cannot find the file specified: 'old_filename.txt' -> 'new_filename.txt'
When the OSError is caught, it’s often helpful to analyze its attributes to gather more information about the cause of the error. Some important attributes include:
- errno: An integer representing the error code.
- strerror: A string providing a description of the error.
- filename: The name of the file that caused the error.
Here’s an example of how to use these attributes to provide a more informative error message:
import os
try:
os.rename("old_filename.txt", "new_filename.txt")
except OSError as e:
print(f"Error (code {e.errno}): {e.strerror}. File: {e.filename}")
Output:
Error (code 2): The system cannot find the file specified. File: old_filename.txt
By handling the OSError exception in this manner, you can ensure your Python program continues to run even when encountering file operation errors and provide more meaningful feedback to the user.
Note: The FileNotFoundError and FileExistsError are children of the OSError. So, you can catch them using the OSError.
Learn important Python functions by watching the following video:
Final Thoughts
Congratulations! You’ve now learned how to rename files in Python like a pro. With the power of the os and shutil modules at your disposal, file manipulation will certainly become a breeze.
Whether you’re organizing files, automating tasks, or creating your own file management system, the ability to rename files programmatically will undoubtedly prove invaluable.
Keep exploring Python’s extensive capabilities, and don’t hesitate to apply this newfound knowledge to your projects!
Frequently Asked Questions
In this section, you’ll find some frequently asked questions you may have when renaming files in Python.
How do I rename a directory in Python?
The os.rename() function can also be used to rename a directory.
Simply provide the current directory path and the new directory path as arguments:
import os
os.rename('path/to/old_directory', 'path/to/new_directory')
Can I use pathlib to rename a file?
pathlib is a module that provides an object-oriented interface for working with file system paths.
You can use the Path.rename() method of the Path class to rename files:
from pathlib import Path
old_file = Path('path/to/old_filename.ext')
new_file = Path('path/to/new_filename.ext')
old_file.rename(new_file)
Remember that this will also raise an error if the new file name already exists, so you might want to check for existence using new_file.exists() before renaming.
How Can I Change File Extensions separately in Python?
When dealing with file names and extensions, it is essential to separate the base file name from the file extension to perform the renaming process effectively.
You can use the os.path and pathlib libraries to achieve this.
To start, let’s import the os library and use the os.path.splitext() function to split the file name and its extension:
import os
filename = "example.txt"
basename, extension = os.path.splitext(filename)
Now, we have the base file name as basename and its extension as extension. With these components separated, you can perform various string manipulations on the base file name. After doing the required changes to the basename, you can create the new filename by appending the original extension to it:
new_basename = "new_example"
new_filename = new_basename + extension
With the new filename ready, you can use the os.rename() function to rename the file:
os.rename(filename, new_filename)
It’s important to note that if the files are not in the working directory, you will need to include the full path in the renaming process.