Python Delete Files 🗑️
Deleting Files & Folders
To delete files, you must import the os module. Always check if a file exists before deleting it to avoid errors.
🗑️ Analogy: The Shredder
Deleting a file in Python is like putting a document in a Paper Shredder.
- Once it's gone, it's gone. There is no "Recycle Bin" or "Undo" button here.
- Be extremely careful!
✨ Delete a File
Use os.remove() to delete a file.
python
import os
if os.path.exists("demofile.txt"):
os.remove("demofile.txt")
print("File deleted")
else:
print("The file does not exist")🎯 Real-World Application: Cleanup
Deleting temporary files after a task is complete to save space.
python
import os
# Delete all .tmp files
files = ["temp1.tmp", "temp2.tmp", "important.doc"]
for file in files:
if file.endswith(".tmp"):
if os.path.exists(file):
os.remove(file)
print(f"Deleted {file}")📂 Delete an Empty Folder
Use os.rmdir() to delete an empty folder.
python
import os
try:
os.rmdir("myfolder")
print("Folder deleted")
except OSError:
print("Folder is not empty or does not exist")⚠️ Delete Folder with Content
To delete a folder containing files, use the shutil module. Warning: This cannot be undone!
python
import shutil
shutil.rmtree("myfolder") # Deletes folder and ALL its contents✨ Pro Tip: Pathlib
Modern Python uses the pathlib module for object-oriented file system paths.
python
from pathlib import Path
file_path = Path("demofile.txt")
if file_path.exists():
file_path.unlink() # Delete file