To delete a file in Python, you cannot use a method from the standard file object. Instead, you must import the os module, and use its built-in os.remove() function.
Key Takeaways: Python provides several robust ways to delete files and folders depending on your specific needs. The os.remove() function handles single files, os.rmdir() handles empty folders, and the shutil module acts as a sledgehammer for completely wiping out folders with content.
The os module provides a portable way of using operating system dependent functionality.
To remove a file, pass the filename (and path, if it's not in the current directory) to os.remove().
import os
# Delete the file named "demofile.txt"
os.remove("demofile.txt")
To avoid getting an error (like a FileNotFoundError), you might want to check if the file exists before trying to delete it. You can do this using os.path.exists().
import osfile_to_delete = "demofile.txt"
if os.path.exists(file_to_delete): os.remove(file_to_delete) print("The file has been deleted.") else: print("The file does not exist!")
os.path.exists() is great, the most Pythonic way to handle file deletion is to use a try-except block. This ensures your program doesn't crash if something unexpected happens (like a permission block from the Operating System).
try:
os.remove("demofile.txt")
except FileNotFoundError:
print("File already deleted or missing.")
except PermissionError:
print("You do not have permission to delete this file.")
To delete an entire folder, use the os.rmdir() method.
Note: You can only remove empty folders using os.rmdir(). If the folder contains files, it will throw an error.
import os
# Delete the folder named "myfolder"
os.rmdir("myfolder")
Which module must you import to delete files and folders in Python?