← Back to Python Course | Chapter 9: File Handling | Lesson 6 of 6

Python Delete Files

Reading and writing files covers most day-to-day file handling, but eventually a file (or an entire folder) needs to be removed entirely -- Python's os module provides os.remove() for a single file and os.rmdir() for an empty folder, while shutil.rmtree() handles a folder and everything inside it.

Deleting a File with os.remove()

os.remove(path) permanently deletes the file at the given path -- there is no built-in undo, so once a file is removed this way, it is genuinely gone (aside from whatever operating-system-level recovery tools might exist outside Python entirely).

Note: Double-check the exact path being passed to os.remove() before running it, especially in scripts that construct paths dynamically -- a mistaken path deletes the wrong file with no warning.

Warning: os.remove() provides no confirmation prompt and no undo -- it deletes immediately and permanently the moment it is called.

Example: Deleting a File with os.remove()

python
import os
with open("temp.txt", "w") as f:
    f.write("data")
os.remove("temp.txt")
print(os.path.exists("temp.txt"))

Checking If a File Exists Before Deleting

os.path.exists(path) returns True if a file or folder exists at that path, and checking it before calling os.remove() avoids a FileNotFoundError crash on a file that was already deleted, never created, or misspelled.

Note: Always check os.path.exists() before deleting when the file's presence is not guaranteed, rather than letting a FileNotFoundError crash the script.

Warning: Skipping the existence check and assuming a file is always present is a common cause of an unhandled crash in cleanup or maintenance scripts.

Example: Checking If a File Exists Before Deleting

python
import os
if os.path.exists("missing.txt"):
    os.remove("missing.txt")
else:
    print("File does not exist")

Deleting an Empty Folder

os.rmdir(path) removes a folder, but only if it is completely empty -- calling it on a folder that still contains files or subfolders raises an OSError, a safety measure that prevents accidentally deleting a folder full of content with a single, simple call.

Note: Empty a folder's contents first (deleting each file individually) before calling os.rmdir() on the now-empty folder itself.

Warning: os.rmdir() refusing to delete a non-empty folder is a deliberate safety feature, not a bug -- it exists specifically to prevent accidental bulk deletion.

Example: Deleting an Empty Folder

python
import os
os.mkdir("empty_dir")
os.rmdir("empty_dir")
print(os.path.exists("empty_dir"))

Deleting a Folder and Everything Inside It

shutil.rmtree(path) removes an entire folder tree at once, including every file and subfolder inside it, regardless of how much content it holds -- far more powerful (and far more dangerous) than os.rmdir(), since it never asks for confirmation before deleting everything.

Note: Reserve shutil.rmtree() specifically for folders you are certain should be completely and permanently removed -- its power makes it easy to delete more than intended if the path is wrong.

Warning: shutil.rmtree() on the wrong path (like a typo pointing one directory too high) can delete far more data than intended, with no confirmation step to catch the mistake.

Example: Deleting a Folder and Everything Inside It

python
import os
import shutil
os.makedirs("full_dir/sub", exist_ok=True)
with open("full_dir/file.txt", "w") as f:
    f.write("data")
shutil.rmtree("full_dir")
print(os.path.exists("full_dir"))

Safer Deletion Patterns

For genuinely important data, a "soft delete" pattern (renaming or moving a file to a designated trash/archive folder instead of truly deleting it) offers a safety net that immediate, permanent deletion does not -- letting a mistake be undone by simply moving the file back.

Note: Consider moving a file to a dedicated "deleted" or "archive" folder instead of truly removing it, whenever the data being deleted might genuinely matter later.

Warning: True, immediate deletion (os.remove or shutil.rmtree) offers no recovery path within Python itself -- a soft-delete pattern is the only way to build in a safety net at the application level.

Example: Safer Deletion Patterns

python
import os
import shutil
os.makedirs("archive", exist_ok=True)
with open("important.txt", "w") as f:
    f.write("data")
shutil.move("important.txt", "archive/important.txt")
print(os.path.exists("archive/important.txt"))
Common Mistakes
  1. Calling os.remove() on a file that does not exist, which raises a FileNotFoundError -- checking os.path.exists() first, or catching the exception, avoids an unhandled crash.
  2. Using os.remove() on a directory (rather than a file), which raises an IsADirectoryError -- directories need os.rmdir() or shutil.rmtree() instead.
  3. Deleting a file without any confirmation or backup in a script handling user data, when a mistake in the delete logic could destroy something irreplaceable.
Chapter Summary
  • os.remove(path) deletes a single file, raising FileNotFoundError if it does not exist.
  • os.path.exists(path) checks whether a file or folder exists before attempting to delete it, avoiding an unhandled exception.
  • os.rmdir(path) removes an empty folder, while shutil.rmtree(path) removes a folder and everything inside it, even if not empty.
Browser Support

os.remove(), os.rmdir(), and shutil.rmtree() are part of Python's standard library and work identically across every Python 3 version and operating system.

🔒

Chapter Quiz — Complete all 6 topics to unlock

0/6 topics done

Complete these topics first:

Login to run this code

C/C++/Java/PHP execution requires a free account. Your code is saved — you'll land right back in the editor after logging in.