πŸ—‘οΈ 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 empty

delete_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! 😊