Welcome to our comprehensive guide on deleting files using Python! This tutorial is designed for beginners and intermediates, so let's dive in. šÆ
In Python, you can delete a file using the os module's os.remove() function. This function takes the file path as its argument and deletes the file.
import os
file_path = "example.txt"
os.remove(file_path)š Note: Make sure the file you want to delete exists before using os.remove(), as it will raise an error if the file doesn't exist.
If you need to delete multiple files, you can use a loop to iterate over a list of file paths.
import os
file_paths = ["file1.txt", "file2.txt", "file3.txt"]
for file_path in file_paths:
os.remove(file_path)Deleting a directory is a bit more complex. You can't directly delete a directory using os.remove(). Instead, you should use os.rmdir(). However, if the directory is not empty, you need to remove its contents first.
import os
dir_path = "my_directory"
# Make sure the directory is empty before deleting
for child in os.listdir(dir_path):
file_path = os.path.join(dir_path, child)
if os.path.isdir(file_path):
os.rmdir(file_path)
else:
os.remove(file_path)
# Now the directory can be removed
os.rmdir(dir_path)š Note: os.path.isdir() checks if the given path is a directory.
Always remember to handle potential errors when deleting files or directories. Python's built-in try/except blocks can help manage these errors.
import os
file_path = "nonexistent_file.txt"
try:
os.remove(file_path)
except FileNotFoundError:
print("The file does not exist.")What function is used to delete a file in Python?
Happy coding! šÆš”š