Question

How to Delete a File or Folder in Python

pythonfile-iodirectorydelete-file

Question

How can I delete a file or folder in Python?

For example, I want to understand the correct way to remove:

  • a single file
  • an empty directory
  • a directory that contains files or subdirectories

I would also like to know which Python modules and functions are typically used for each case.

Short Answer

By the end of this page, you will understand how Python deletes files and directories, when to use os.remove(), os.rmdir(), shutil.rmtree(), and modern pathlib methods, plus how to avoid common deletion mistakes.

Concept

Deleting something in Python depends on what kind of path you are deleting.

  • A file is deleted differently from a directory.
  • An empty directory is deleted differently from a non-empty directory.
  • Python provides multiple tools for this, mainly from:
    • os
    • shutil
    • pathlib

The core idea is simple:

  • Use file deletion functions for files.
  • Use directory deletion functions for folders.
  • Use recursive deletion only when you want to remove a folder and everything inside it.

This matters because deleting the wrong path the wrong way causes errors such as:

  • FileNotFoundError
  • IsADirectoryError
  • NotADirectoryError
  • OSError when trying to remove a non-empty directory

In real programming, deletion is common when:

  • cleaning up temporary files
  • removing generated reports
  • clearing upload folders
  • resetting test environments
  • deleting cache directories

Because deletion is destructive, good Python code usually includes checks, clear intent, and error handling.

Mental Model

Think of your filesystem like a house:

  • A file is like a single item, such as a book.
  • An empty folder is like an empty box.
  • A folder with contents is like a box full of smaller boxes and items.

Now imagine three different actions:

  • os.remove() or Path.unlink() = throw away one item
  • os.rmdir() or Path.rmdir() = throw away an empty box
  • shutil.rmtree() = throw away the entire box and everything inside it

If you try to throw away a full box using the "empty box" action, Python stops you. That safety rule prevents accidental data loss.

Take Quiz

Syntax and Examples

Core syntax

import os
import shutil
from pathlib import Path

Delete a file

Using os:

import os

os.remove("notes.txt")

Using pathlib:

from pathlib import Path

Path("notes.txt").unlink()

Delete an empty folder

Using os:

import os

os.rmdir("empty_folder")

Using pathlib:

from pathlib import Path

Path("empty_folder").rmdir()

Delete a folder and everything inside it

import shutil

shutil.rmtree("old_project")

Beginner-friendly example

from pathlib import Path
import shutil

file_path = Path("example.txt")
folder_path = Path("example_folder")

if file_path.exists() and file_path.is_file():
    file_path.unlink()

if folder_path.exists() and folder_path.is_dir():
    shutil.rmtree(folder_path)

What this does

  • Checks whether example.txt exists and is a file
  • Deletes it with unlink()
  • Checks whether example_folder exists and is a directory
  • Deletes the whole directory tree with shutil.rmtree()

This is safer than blindly calling delete functions on unknown paths.

Step by Step Execution

Example

from pathlib import Path

file_path = Path("report.txt")

if file_path.exists():
    file_path.unlink()
    print("File deleted")
else:
    print("File not found")

Step-by-step

  1. from pathlib import Path

    • Imports the Path class for working with filesystem paths.
  2. file_path = Path("report.txt")

    • Creates a path object pointing to report.txt.
    • This does not delete anything yet.
  3. if file_path.exists():

    • Checks whether the file actually exists.
    • If it does not exist, the else block will run.
  4. file_path.unlink()

    • Deletes the file.
    • If report.txt is a normal file, it is removed from the filesystem.
  5. print("File deleted")

    • Confirms the action.
  6. else: print("File not found")

    • Runs when the file does not exist.

Small trace

Assume report.txt exists before the script runs.

  • file_path points to report.txt
  • exists() returns True
  • unlink() removes the file
  • File deleted is printed

If the file does not exist:

  • exists() returns False
  • unlink() is never called
  • File not found is printed

Real World Use Cases

Common practical uses

Cleaning up temporary files

Scripts often create temporary CSV, log, or export files that should be removed after processing.

import os

if os.path.exists("temp.csv"):
    os.remove("temp.csv")

Resetting a cache directory

Applications may clear a generated cache folder before rebuilding it.

import shutil

shutil.rmtree("cache", ignore_errors=True)

Removing uploaded files

A web app may delete old uploads when a user replaces a profile picture.

Cleaning test data

Automated tests often create files and directories, then delete them during teardown.

Deleting generated build output

Development tools may remove folders like dist/, build/, or temporary artifacts before a new run.

Take Quiz

Real Codebase Usage

In real projects, developers usually do more than call a delete function directly.

Common patterns

Guard clauses

Check the path type before deleting.

from pathlib import Path
import shutil

path = Path("data")

if not path.exists():
    print("Nothing to delete")
elif path.is_file():
    path.unlink()
elif path.is_dir():
    shutil.rmtree(path)

Validation before destructive actions

Programs often make sure the target is inside an expected directory to avoid deleting the wrong location.

from pathlib import Path

base = Path("/safe/workspace").resolve()
target = (base / "old_logs").resolve()

if base in target.parents:
    print("Target is inside workspace")

Error handling

Deletion can fail because of permissions, file locks, or missing paths.

from pathlib import Path

try:
    Path("locked_file.txt").unlink()
except FileNotFoundError:
    print("File already removed")
except PermissionError:
    print("Not allowed to delete this file")

Cleanup in scripts and tests

Deletion is often used in finally blocks so cleanup happens even if something fails.

from pathlib import Path

file_path = Path("output.txt")

try:
    file_path.write_text("hello")
    # do work
finally:
    if file_path.exists():
        file_path.unlink()

Recursive deletion for generated directories

shutil.rmtree() is common when deleting known temporary directories created by the application itself.

Common Mistakes

1. Using os.remove() on a folder

Broken code:

import os

os.remove("my_folder")

Why it fails:

  • os.remove() is for files, not directories.

Use this instead:

import os

os.rmdir("my_folder")

Or, if the folder is not empty:

import shutil

shutil.rmtree("my_folder")

2. Trying to remove a non-empty directory with os.rmdir()

Broken code:

import os

os.rmdir("project")

Why it fails:

  • os.rmdir() only removes empty directories.

Fix:

import shutil

shutil.rmtree("project")

3. Deleting without checking what the path is

Broken code:

from pathlib import Path

path = Path("data")
path.unlink()

Why it fails:

  • If data is a directory, unlink() is the wrong method.

Safer version:

from pathlib import Path
import shutil

path = Path("data")

if path.is_file():
    path.unlink()
elif path.is_dir():
    shutil.rmtree(path)

4. Forgetting that deletion is permanent

shutil.rmtree() removes a directory tree recursively. Beginners sometimes test it on important folders.

How to avoid this:

  • Print the path before deleting
  • Validate the path
  • Test in a safe temporary folder first

5. Ignoring exceptions

Broken code:

from pathlib import Path

Path("missing.txt").unlink()

Possible problem:

  • Raises FileNotFoundError if the file does not exist.

Safer version:

from pathlib import Path

file_path = Path("missing.txt")
if file_path.exists():
    file_path.unlink()

6. Confusing relative and absolute paths

A relative path like "logs/error.log" is resolved from the current working directory, which may not be what you expect.

Tip:

from pathlib import Path

print(Path.cwd())

Comparisons

Deletion methods in Python

TaskRecommended toolWorks on files?Works on empty dirs?Works on non-empty dirs?
Delete one fileos.remove() / Path.unlink()YesNoNo
Delete one empty directoryos.rmdir() / Path.rmdir()NoYesNo
Delete directory tree recursivelyshutil.rmtree()NoYesYes

os vs pathlib

Featureospathlib
StyleFunction-basedObject-oriented
ReadabilityGoodOften clearer for beginners
File deletionos.remove(path)Path(path).unlink()
Empty dir deletionos.rmdir(path)Path(path).rmdir()
Recursive dir deletionUse shutil.rmtree()Still usually use shutil.rmtree()

Which should you use?

  • Use pathlib when you want clearer path handling.
  • Use os if you are working in older codebases or simpler scripts.
  • Use shutil.rmtree() when you intentionally need recursive folder deletion.
Take Quiz

Cheat Sheet

# Delete a file
import os
os.remove("file.txt")

from pathlib import Path
Path("file.txt").unlink()

# Delete an empty folder
os.rmdir("empty_folder")
Path("empty_folder").rmdir()

# Delete a folder with contents
import shutil
shutil.rmtree("folder_name")

Rules

  • os.remove() and Path.unlink() are for files
  • os.rmdir() and Path.rmdir() are for empty directories only
  • shutil.rmtree() is for directories and all contents
  • Deletion can raise exceptions if the path is missing, locked, or protected

Useful checks

path.exists()
path.is_file()
path.is_dir()

Common exceptions

  • FileNotFoundError — path does not exist
  • PermissionError — not allowed to delete it
  • OSError — often happens when directory is not empty or system-level deletion fails

Safety tips

  • Check the path before deleting
  • Be careful with relative paths
  • Test recursive deletion in a safe folder first

FAQ

How do I delete a file in Python?

Use os.remove("file.txt") or Path("file.txt").unlink().

How do I delete an empty folder in Python?

Use os.rmdir("folder") or Path("folder").rmdir().

How do I delete a non-empty folder in Python?

Use shutil.rmtree("folder") to remove the folder and everything inside it.

What is the difference between os.remove() and os.rmdir()?

os.remove() deletes files. os.rmdir() deletes empty directories.

Is shutil.rmtree() dangerous?

Yes. It recursively deletes everything inside the target directory, so you should validate the path carefully before using it.

Should I use os or pathlib for deletion?

Both work. pathlib is often easier to read, especially for beginners.

What happens if the file does not exist?

Python usually raises FileNotFoundError unless you check first or handle the exception.

Can Python send deleted files to the recycle bin?

Not with the standard deletion functions shown here. These functions permanently remove paths from the filesystem's normal view.

Take Quiz

Mini Project

Description

Build a small cleanup script that deletes a file if it exists and removes a temporary folder if it exists. This demonstrates the difference between deleting a file and deleting a directory tree, which is a very common maintenance task in scripts, automation, and tests.

Goal

Create a Python script that safely removes a target file and a target folder, printing clear messages for each action.

Requirements

  • Define one path for a file and one path for a folder
  • Check whether each path exists before trying to delete it
  • Delete the file with the correct file deletion method
  • Delete the folder with the correct directory deletion method
  • Print a message describing what happened for each path
Take Quiz

Keep learning

Related questions

View more