In this tutorial, we will be exploring the rename()
method in Python. This function is a part of Python’s built-in os module and it allows you to rename files or directories.
How to Use the rename() Method
The syntax for using the rename()
method is as follows:
import os
os.rename(src, dst)
In this code snippet, ‘src’ refers to the source file name (the current name of the file), while ‘dst’ represents the destination file name (the new name you want to give to your file).
An Example of rename() Usage
import os
# renaming a single file
os.rename('old_file.txt', 'new_file.txt')
This script will change the name of ‘old_file.txt’ to ‘new_file.txt’. It’s important to note that both old_file.txt and new_file.txt should be in the same directory where your python script is running. If they are located elsewhere, you need to specify their full path.
Error Handling with rename()
If either ‘src’ or ‘dst’ does not exist or if ‘src’ is a directory but ‘dst’ is an existing file, then Python will raise an OSError exception. To handle these exceptions gracefully, we can use try-except blocks:
import os
try:
os.rename('old_dir', 'new_dir')
except OSError as e:
print(f"Error: {e.strerror}")
Rename Multiple Files with rename()
Python’s rename()
method can also be used to rename multiple files in a directory. Here is an example:
import os
def rename_files():
for count, filename in enumerate(os.listdir("dir")):
dst ="new_name" + str(count) + ".txt"
src ='dir/'+ filename
dst ='dir/'+ dst
# rename all the files
os.rename(src, dst)
# Driver Code
if __name__ == '__main__':
rename_files()
This script will rename all the .txt files in the specified directory (‘dir’) to ‘new_name’ followed by a number.
Conclusion
The rename()
function is a powerful tool that allows you to change file or directory names programmatically. It’s simple and easy to use, making it a valuable addition to your Python toolkit.