Renaming and removing files in Python are common file operations that can be performed using functions from the os
and os.path
modules. Here’s a detailed overview of how to perform these operations, including examples.
To rename a file, you can use the os.rename()
function. This function requires two arguments: the current file name and the new file name.
import os
os.rename('current_filename', 'new_filename')
import os
# Renaming a file
try:
os.rename('old_name.txt', 'new_name.txt')
print("File renamed successfully.")
except FileNotFoundError:
print("The file to be renamed does not exist.")
except PermissionError:
print("You do not have permission to rename this file.")
except Exception as e:
print(f"An unexpected error occurred: {e}")
To remove (delete) a file, you can use the os.remove()
function. This function requires one argument: the name of the file to be removed.
import os
os.remove('filename')
import os
# Removing a file
try:
os.remove('file_to_remove.txt')
print("File removed successfully.")
except FileNotFoundError:
print("The file to be removed does not exist.")
except PermissionError:
print("You do not have permission to remove this file.")
except Exception as e:
print(f"An unexpected error occurred: {e}")