Working with Files: Rename a File in Python
Have you ever experienced the tiring task of renaming a file especially when you are coding because you have to take a break, go to the file and then rename it? It may sound easy but doing that too many times will make it a tedious task.
But fear not, there is an easy way to do that and you can rename a file in your code itself in Python. In this 'working with files' module, till now you must've learned the following:
- Read from a text file in Python
- Write to a text file in Python
- Create a new text file in Python
- Check if a file exists in Python
- Read CSV files in Python
- Write CSV files in Python
And in this article, you will be learning to rename a file in Python. Without further ado, let's get started.
Procedure to Rename a File in Python:
Let's go through the process of renaming a file in Python step by step:
- Import the 'os' module:
>>> import os
- Specify the current file name and the desired new file name:
>>> current_file_name = "file.txt"
>>> new_file_name = "new_file.txt"
- Rename the file using the 'os.rename()' function:
>>> os.rename(current_file_name, new_file_name)
>>> current_file_name = "/path/to/current_file.txt"
>>> new_file_name = "/path/to/new_file.txt"
- Handle any exceptions: It's always good to handle potential exceptions that may occur during the file renaming process. For example, if the file doesn't exist or if there are permission issues, you may want to provide an appropriate error handling code. Here's an example of how you can handle the exceptions using a try-except block:
>>> try:
>>> os.rename(current_file_name, new_file_name)
>>> print("File renamed successfully.")
>>> except FileNotFoundError:
>>> print("File not found.")
>>> except PermissionError:
>>> print("Permission denied. Unable to rename the file.")
This code will catch the specific exceptions raised when a file is not found or when there are permission issues. You can customize the error messages or add more specific exception handling as needed.
Conclusion:
In conclusion, renaming a file in Python is as simple as it is but you have to remember to give the necessary permissions to modify files in the specified directory. Make sure to exercise caution when renaming files especially if there are sensitive data in them. If you have any questions or doubts, feel free to contact us.