How to rename a file in Python
How to rename a file in Python.
Here's a step-by-step tutorial on how to rename a file in Python:
Step 1: Import the os module
First, we need to import the os module, which provides a way to interact with the operating system. It includes functions for file operations like renaming files.
import os
Step 2: Provide the current and new file names
Next, we need to specify the current name of the file we want to rename and the new name we want to give it. You can either hardcode the file names or get them dynamically from user input or other sources.
current_name = "old_file.txt"
new_name = "new_file.txt"
Step 3: Use the os.rename() function
Now, we can use the os.rename() function to rename the file. This function takes two arguments: the current file name and the new file name.
os.rename(current_name, new_name)
Step 4: Handling errors
It's important to handle potential errors that may occur during the file renaming process. One common error is if the file does not exist. We can catch the FileNotFoundError exception and display a meaningful error message.
try:
os.rename(current_name, new_name)
except FileNotFoundError:
print("The file does not exist.")
Additional Tips and Examples
Renaming multiple files
If you want to rename multiple files, you can use a loop to iterate over a list of file names and rename them one by one. Here's an example:
file_names = ["file1.txt", "file2.txt", "file3.txt"]
for current_name in file_names:
new_name = current_name.replace("file", "new_file")
os.rename(current_name, new_name)
In this example, we replace the word "file" with "new_file" in the new file names.
Moving files to a different directory
If you want to move the file to a different directory while renaming it, you can specify the full path of the new file name. Here's an example:
current_name = "file.txt"
new_directory = "/path/to/new_directory/"
new_name = new_directory + "new_file.txt"
os.rename(current_name, new_name)
In this example, we provide the full path of the new file name, including the directory.
That's it! You now know how to rename a file in Python using the os.rename() function.