Table of Contents
ToggleIn Python, you can rename and delete files using built-in functions from the os module. These operations are important when managing files within a file system. In this tutorial, we will explore how to perform these actions step-by-step.
To rename a file in Python, you can use the os.rename() function. This function takes two arguments: the current filename and the new filename.
Following is the basic syntax of the rename() function in Python −
os.rename(current_file_name, new_file_name)
Following are the parameters accepted by this function −
Following is an example to rename an existing file “oldfile.txt” to “newfile.txt” using the rename() function −
import os
# Current file name
current_name = "oldfile.txt"
# New file name
new_name = "newfile.txt"
# Rename the file
os.rename(current_name, new_name)
print(f"File '{current_name}' renamed to '{new_name}' successfully.")
Output:
File ‘oldfile.txt’ renamed to ‘newfile.txt’ successfully.
You can delete a file in Python using the os.remove() function. This function deletes a file specified by its filename.
Following is the basic syntax of the remove() function in Python −
os.remove(file_name)
This function accepts the name of the file as a parameter which needs to be deleted.
Following is an example to delete an existing file “file_to_delete.txt” using the remove() function −
import os
# File to be deleted
file_to_delete = "file_to_delete.txt"
# Delete the file
os.remove(file_to_delete)
print(f"File '{file_to_delete}' deleted successfully.")
Output:
File ‘file_to_delete.txt’ deleted successfully.
Key Takeaway: Use os.rename() to rename files and os.remove() to delete them—simple yet powerful tools for file management in Python!
