Introduction
Renaming files in Python can be done easily using the os
module, which provides a portable way of using operating system-dependent functionality. The os.rename()
function is used to rename files and directories.
Using os.rename()
The os.rename()
function takes two arguments: the current file name and the new file name.
Syntax
import os
os.rename('old_file_name.txt', 'new_file_name.txt')
Example
Let’s say you have a file named example.txt
and you want to rename it to renamed_example.txt
.
import os
# Renaming the file
os.rename('example.txt', 'renamed_example.txt')
# Verify the file has been renamed
if os.path.exists('renamed_example.txt'):
print("File renamed successfully.")
else:
print("File renaming failed.")
Output
File renamed successfully.
Handling Exceptions
It’s a good practice to handle exceptions that may occur during the renaming process, such as file not found errors or permission errors.
Example
import os
try:
os.rename('example.txt', 'renamed_example.txt')
print("File renamed successfully.")
except FileNotFoundError:
print("The file does not exist.")
except PermissionError:
print("Permission denied.")
except Exception as e:
print(f"An error occurred: {e}")
Output
The file does not exist.
Renaming Files in a Directory
You can rename multiple files in a directory by iterating over the files and using the os.rename()
function.
Example
Let’s rename all .txt
files in a directory by adding a prefix new_
.
import os
directory = 'test_directory'
prefix = 'new_'
# Get the list of files in the directory
files = os.listdir(directory)
# Iterate over the files and rename them
for file_name in files:
if file_name.endswith('.txt'):
old_file_path = os.path.join(directory, file_name)
new_file_path = os.path.join(directory, prefix + file_name)
os.rename(old_file_path, new_file_path)
# Verify the files have been renamed
print("Files renamed successfully.")
Output
Files renamed successfully.
Using pathlib for Renaming Files
The pathlib
module in Python 3.4+ provides an object-oriented approach for handling filesystem paths. It can also be used to rename files.
Example
from pathlib import Path
# Define the path
file_path = Path('example.txt')
# Rename the file
file_path.rename('renamed_example.txt')
# Verify the file has been renamed
if Path('renamed_example.txt').exists():
print("File renamed successfully.")
else:
print("File renaming failed.")
Output
File renamed successfully.
Conclusion
Renaming files in Python is a simple and efficient process using the os
module or the pathlib
module. By using these modules, you can rename individual files, handle exceptions, and rename multiple files in a directory. Understanding how to rename files is essential for file management tasks in Python applications.