Renaming Files in Python
Renaming files in Python is a simple and straightforward process. The os
module provides a function called rename()
that allows you to rename files.
Here’s an example:
import os
# Specify the current file name
current_name = "old_file.txt"
# Specify the new file name
new_name = "new_file.txt"
# Rename the file
os.rename(current_name, new_name)
In this example, we first import the os
module. Then, we specify the current name of the file we want to rename and the new name we want to give it. Finally, we call the rename()
function and pass in the current name and the new name as arguments.
It’s important to note that the file you want to rename should be in the same directory as your Python script, or you should provide the full path to the file.
Deleting Files in Python
Deleting files in Python is also done using the os
module. The os
module provides a function called remove()
that allows you to delete files.
Here’s an example:
import os
# Specify the file name
file_name = "file_to_delete.txt"
# Delete the file
os.remove(file_name)
In this example, we import the os
module and specify the name of the file we want to delete. Then, we call the remove()
function and pass in the file name as an argument.
Similar to renaming files, the file you want to delete should be in the same directory as your Python script, or you should provide the full path to the file.
Handling Errors
When renaming or deleting files in Python, it’s important to handle errors that may occur. For example, if the file you want to rename or delete does not exist, you will encounter an error.
Here’s an example of how to handle such errors:
import os
# Specify the file name
file_name = "nonexistent_file.txt"
try:
# Rename the file
os.rename(file_name, "new_file.txt")
except FileNotFoundError:
print("File not found.")
except PermissionError:
print("Permission denied.")
In this example, we use a try-except
block to catch any errors that may occur when renaming the file. If the file is not found, a FileNotFoundError
will be raised, and we print a corresponding message. If we don’t have permission to rename the file, a PermissionError
will be raised, and we print a different message.
By handling errors, you can ensure that your script doesn’t crash if something goes wrong during the renaming or deleting process.
Conclusion
Renaming and deleting files in Python is a simple task thanks to the os
module. By using the rename()
function, you can easily change the name of a file, while the remove()
function allows you to delete files. Remember to handle any errors that may occur to ensure the smooth execution of your script.