coding
folder
delete
python

How can I delete a file or folder in Python?

Master System Design with Codemia

Enhance your system design skills with over 120 practice problems, detailed solutions, and hands-on exercises.

Introduction

Deleting files and directories in Python is straightforward once you separate three cases: deleting one file, deleting an empty directory, and deleting a directory tree. Each case uses a different API, and choosing the wrong one usually raises an exception instead of doing something helpful.

For modern Python code, pathlib is usually the clearest option, while os and shutil remain important for lower-level or recursive operations. The safest solution depends on whether you want to fail loudly, ignore missing paths, or remove everything below a directory.

Delete A Single File

For one file, use Path.unlink() or os.remove().

python
1from pathlib import Path
2
3file_path = Path("example.txt")
4
5if file_path.is_file():
6    file_path.unlink()
7    print("Deleted file")
8else:
9    print("File not found")

The same operation with os.remove() looks like this:

python
1import os
2
3file_path = "example.txt"
4
5if os.path.isfile(file_path):
6    os.remove(file_path)

Both approaches remove a file. Neither will delete a directory.

Delete An Empty Directory

If the target is an empty directory, use rmdir().

python
1from pathlib import Path
2
3folder = Path("empty_folder")
4
5if folder.is_dir():
6    folder.rmdir()
7    print("Deleted empty folder")

You can also use os.rmdir(). The critical rule is that rmdir() only works when the directory contains nothing. If files or subdirectories remain inside, Python raises an error.

Delete A Non-Empty Directory Tree

If you want to remove a directory and everything below it, use shutil.rmtree().

python
1import shutil
2from pathlib import Path
3
4folder = Path("build")
5
6if folder.exists() and folder.is_dir():
7    shutil.rmtree(folder)
8    print("Deleted folder tree")

This is intentionally powerful. It removes all files and subdirectories recursively, so it is the method to use for cache folders, generated output, or disposable working directories.

Prefer pathlib For Readable Code

pathlib often makes deletion code easier to read because path operations stay attached to the path object itself.

python
1from pathlib import Path
2
3base = Path("logs")
4target = base / "latest.log"
5
6if target.exists() and target.is_file():
7    target.unlink()

That style scales well when you are creating, inspecting, and deleting paths in the same function.

Handle Missing Paths Deliberately

You do not always need an existence check before deletion. In cleanup code, it is often better to attempt the operation and catch the specific exception.

python
1from pathlib import Path
2
3file_path = Path("example.txt")
4
5try:
6    file_path.unlink()
7except FileNotFoundError:
8    print("Nothing to delete")

This avoids a race condition where the file exists during the check but disappears before the deletion call. In concurrent systems, exception-based handling is often more reliable than a separate exists() check.

One Helper For Files And Folders

If you want a utility function that handles both files and directories, keep the behavior explicit.

python
1from pathlib import Path
2import shutil
3
4def delete_path(path_str):
5    path = Path(path_str)
6
7    if path.is_file():
8        path.unlink()
9    elif path.is_dir():
10        shutil.rmtree(path)
11    else:
12        raise FileNotFoundError(f"No such path: {path}")
13
14delete_path("temp.txt")
15delete_path("old_reports")

That helper treats any directory as recursive deletion. If that is too aggressive for your use case, swap in path.rmdir() and let non-empty directories fail instead.

Common Pitfalls

  • Calling unlink() or os.remove() on a directory.
  • Using rmdir() on a directory that still contains files.
  • Running shutil.rmtree() without realizing it deletes the whole tree.
  • Assuming an exists() check guarantees the path will still be there a moment later.
  • Mixing string-based paths everywhere when pathlib would make the code clearer.

Summary

  • Use Path.unlink() or os.remove() to delete a file.
  • Use Path.rmdir() or os.rmdir() only for empty directories.
  • Use shutil.rmtree() to remove a non-empty directory tree.
  • Prefer pathlib in new code because path handling is easier to read.
  • In cleanup code, catching FileNotFoundError is often safer than a separate existence check.

Course illustration
Course illustration

All Rights Reserved.