ποΈ Python File Handling β Deleting Files
Introduction π
Python provides simple and safe ways to delete files from your system using the built-in os and pathlib modules. File deletion is essential for cleaning temporary data, logs, old backups, and unused files.
Note
β οΈ Deleted files CANNOT be recovered through Python. Always double-check before deleting.
1. Delete a File Using os.remove() π§±
os_remove.py
import os
os.remove("data.txt") # deletes file named data.txtβ File must exist, otherwise Python raises FileNotFoundError.
2. Handling Missing Files Safely π‘οΈ
safe_delete.py
import os
filename = "data.txt"
if os.path.exists(filename):
os.remove(filename)
print("Deleted:", filename)
else:
print("β File does not exist!")Note
β Always check before deleting to avoid errors.
3. Delete Files Using pathlib (Modern Method) π
pathlib_delete.py
from pathlib import Path
file = Path("data.txt")
if file.exists():
file.unlink()
print("File deleted!")
else:
print("β File not found!")β unlink() = delete file (same as os.remove())
4. Delete Multiple Files π―
delete_multiple.py
import os
files = ["a.txt", "b.txt", "c.txt"]
for f in files:
if os.path.exists(f):
os.remove(f)
print("Deleted:", f)
else:
print(f, "not found")5. Delete All Files in a Folder (Careful!) β οΈ
delete_all_files.py
import os
folder = "logs"
for file in os.listdir(folder):
path = os.path.join(folder, file)
if os.path.isfile(path):
os.remove(path)
print("Deleted:", path)Note
β οΈ Be very careful β this removes EVERYTHING inside the folder.
6. Delete Files Matching a Pattern π
delete_pattern.py
import os
import glob
for file in glob.glob("*.log"):
os.remove(file)
print("Deleted:", file)β Deletes all .log files in the folder.
7. Delete Temporary Files π§Ή
delete_temp.py
import os
temp_files = ["temp1.tmp", "temp2.tmp"]
for f in temp_files:
if os.path.exists(f):
os.remove(f)8. TryβExcept for Safe Deletion π§©
try_except_delete.py
import os
try:
os.remove("data.txt")
print("File deleted")
except FileNotFoundError:
print("β File not found!")
except PermissionError:
print("β No permission to delete this file!")β Helps avoid application crashes.
9. Delete File After Processing π
process_and_delete.py
import os
filename = "task.txt"
with open(filename) as file:
print(file.read())
os.remove(filename)
print("File deleted after processing")10. Delete Directory (Folder) ποΈ
β You CANNOT delete folders using os.remove().
β Use os.rmdir() or shutil.rmtree().
delete_folder.py
import os
os.rmdir("empty_folder") # folder must be emptydelete_folder_recursive.py
import shutil
shutil.rmtree("myfolder") # deletes folder and all contents!Note
β οΈ shutil.rmtree() is irreversible β be extremely careful!
11. Real-World Example: Auto-Deleting Old Log Files π
delete_old_logs.py
import os
from pathlib import Path
logs = Path("logs")
for log in logs.glob("*.log"):
if log.stat().st_size > 2_000_000: # bigger than 2 MB
log.unlink()
print("Deleted large log file:", log)12. Best Practices π‘
- β Always check if file exists before deleting
- β Use pathlib β cleaner and modern
- β Use tryβexcept to avoid program crashes
- β Never delete directories using os.remove()
- β Be cautious with wildcard (glob) deletion
- β Avoid deleting user files without confirmation
Conclusion π
>>βDeleting files is powerful β use it wisely. Python gives you full control, but with great power comes great responsibility.β β¨
You now fully understand Deleting Files in Python! Want the next topic? Try Append Files, File Modes, JSON Handling, CSV Files, or Directories. Just tell me! π