In Python, the os
module provides various functions for interacting with the operating system. One commonly used function is os.rename()
, which allows you to rename a file using Python code.
Syntax
The syntax of os.rename()
is as follows:
os.rename(src, dst)
Here, src
is the current name of the file or directory, and dst
is the new name that you want to assign to the file or directory.
Example
Let’s consider a simple example where we want to rename a file named “old_name.txt” to “new_name.txt”.
import os
old_name = "old_name.txt"
new_name = "new_name.txt"
os.rename(old_name, new_name)
In the code snippet above, we first import the os
module. Then, we define the old and new names of the file we want to rename. Finally, we call os.rename()
with the old and new names as arguments to rename the file.
Error Handling
It’s important to note that the os.rename()
function can raise an exception if there are any errors during the renaming process. Some common exceptions include FileNotFoundError
if the source file doesn’t exist or PermissionError
if the code doesn’t have the required permissions to rename the file.
To handle exceptions, you can use a try-except block:
import os
old_name = "old_name.txt"
new_name = "new_name.txt"
try:
os.rename(old_name, new_name)
except FileNotFoundError:
print("File not found!")
except PermissionError:
print("Permission denied!")
In the example above, we catch the FileNotFoundError
and PermissionError
exceptions separately and print an appropriate error message.
Conclusion
Using the os.rename()
function in Python, you can easily rename files or directories programmatically. It’s a powerful feature that can come in handy when dealing with file management tasks in your Python applications. Make sure to handle exceptions appropriately to handle any potential errors that may occur during the renaming process.