How to delete a file in Python

Learn how to delete a file in Python. This guide covers various methods, tips, real-world applications, and how to debug common errors.

How to delete a file in Python
Published on: 
Fri
Feb 6, 2026
Updated on: 
Tue
Feb 10, 2026
The Replit Team Logo Image
The Replit Team

File deletion is a common task in Python to manage temporary data or clean up directories. Python's os module offers simple and effective functions to handle this process securely.

You'll learn several techniques to remove files and directories. The article covers practical tips, real-world applications, and common debugging advice to help you handle your file system with confidence.

Using os.remove() to delete a file

import os

file_path = "example.txt"
with open(file_path, "w") as f:
f.write("Test content")

os.remove(file_path)
print(f"File '{file_path}' has been deleted")--OUTPUT--File 'example.txt' has been deleted

The os.remove() function is Python's standard tool for deleting a single file. It directly targets a file specified by its path and removes it from the file system. This method is straightforward and efficient for simple deletion tasks.

It's important to note that os.remove() will raise a FileNotFoundError if the target file doesn't exist. The example code first creates example.txt to guarantee the deletion succeeds. This is a common practice in scripts to avoid runtime errors when cleaning up files.

Basic file deletion techniques

Building on the basics of os.remove(), you'll find that Python's ecosystem provides several other ways to manage files and even remove entire directory trees.

Using os.unlink() as an alternative

import os

file_path = "example.txt"
with open(file_path, "w") as f:
f.write("Test content")

os.unlink(file_path)
print(f"File '{file_path}' has been deleted")--OUTPUT--File 'example.txt' has been deleted

You might be wondering how os.unlink() differs from os.remove(). The short answer is—it doesn't. They are functionally identical in Python's os module. The name unlink is a nod to its Unix origins, where it's the traditional system call for removing a file.

  • Both functions delete a single file specified by its path.
  • Both will raise a FileNotFoundError if the target file doesn't exist.

Python provides both for cross-platform consistency, so choosing between them is purely a matter of style or convention.

Deleting files with pathlib.Path

from pathlib import Path

file_path = Path("example.txt")
file_path.write_text("Test content")

file_path.unlink()
print(f"File '{file_path}' has been deleted")--OUTPUT--File 'example.txt' has been deleted

The pathlib module offers a modern, object-oriented way to handle file system paths. Instead of passing a string path to a function, you create a Path object and call methods like unlink() directly on it.

  • This approach often leads to more readable and intuitive code, as operations are tied directly to the file object.
  • Like its os counterparts, pathlib.Path.unlink() will raise a FileNotFoundError if the file doesn't exist, so the behavior is consistent.

Removing directories with shutil.rmtree()

import os
import shutil

os.makedirs("test_dir", exist_ok=True)
with open("test_dir/file.txt", "w") as f:
f.write("Test content")

shutil.rmtree("test_dir")
print("Directory 'test_dir' and all its contents have been deleted")--OUTPUT--Directory 'test_dir' and all its contents have been deleted

When you need to remove an entire directory and all its contents, Python's shutil module provides the powerful shutil.rmtree() function. Unlike functions that only target single files, rmtree()—short for "remove tree"—deletes a directory and everything within it.

  • This function recursively removes the specified directory, including all subdirectories and files.
  • Because this operation is irreversible, you should use it with caution to avoid accidentally deleting important data.

Advanced file deletion techniques

Beyond simple deletions, you'll often need more resilient logic to handle files that might not exist or to remove multiple files in a single operation.

Safely handling exceptions during deletion

import os

file_path = "nonexistent_file.txt"
try:
os.remove(file_path)
print(f"File '{file_path}' has been deleted")
except FileNotFoundError:
print(f"Error: The file '{file_path}' does not exist")
except PermissionError:
print(f"Error: No permission to delete '{file_path}'")--OUTPUT--Error: The file 'nonexistent_file.txt' does not exist

When deleting files, it's wise to prepare for issues like a missing file or incorrect permissions. Instead of letting your script crash, you can use a try...except block to handle these problems gracefully. This makes your code more robust by anticipating and managing errors without halting execution.

  • The FileNotFoundError exception is triggered if the file you're trying to delete doesn't exist.
  • A PermissionError occurs if your script lacks the necessary rights to remove the file.

By catching these specific exceptions, you can provide clear feedback or log the issue while allowing your program to continue running.

Checking file existence before deletion

import os

file_path = "example.txt"
if os.path.exists(file_path):
os.remove(file_path)
print(f"File '{file_path}' has been deleted")
else:
print(f"The file '{file_path}' does not exist")--OUTPUT--The file 'example.txt' does not exist

Another way to avoid errors is to check if a file exists before trying to delete it. The os.path.exists() function handles this neatly. It returns True if the file is found, letting you proceed with the deletion inside an if block. If it returns False, your code can simply skip the deletion or print a message, completely avoiding a FileNotFoundError.

  • This method is often more direct than a try...except block for this specific task.
  • It makes your code's intent very clear—you're explicitly checking for the file first.

Deleting multiple files with pattern matching

import os
import glob

# Create some test files
for i in range(3):
with open(f"test_{i}.txt", "w") as f:
f.write(f"Content {i}")

# Delete all matching files
for file_path in glob.glob("test_*.txt"):
os.remove(file_path)
print(f"Deleted: {file_path}")--OUTPUT--Deleted: test_0.txt
Deleted: test_1.txt
Deleted: test_2.txt

When you need to delete multiple files at once, like log files or temporary data, the glob module is your go-to tool. It finds all pathnames matching a specified pattern, making batch operations simple and efficient.

  • The function glob.glob("test_*.txt") uses the * wildcard to gather a list of all files that start with test_ and end with .txt.
  • Your script can then loop through this list and call os.remove() on each file path, cleaning up multiple files in just a few lines of code.

Move faster with Replit

Replit is an AI-powered development platform that transforms natural language into working applications. Describe what you want to build, and Replit Agent creates it—complete with databases, APIs, and deployment.

For the file deletion techniques we've explored, Replit Agent can turn them into production-ready tools:

  • Build a temporary file cleaner that uses glob to find and remove old log or cache files.
  • Create a data pipeline that automatically deletes raw data files with os.remove() after they are processed and stored.
  • Deploy a project cleanup utility that uses shutil.rmtree() to reset a directory to its original state.

Describe your app idea, and Replit Agent writes the code, tests it, and fixes issues automatically, all in your browser.

Common errors and challenges

Even with the right tools, you can run into tricky situations like open files, permission issues, or race conditions during deletion.

  • Handling files that are still open: Trying to use os.remove() on a file that's still open can cause issues, especially on Windows where it often raises a PermissionError. It's best to ensure your program closes any file handles, ideally by using a with statement, before attempting deletion. This guarantees the file is released by your script and ready to be removed.
  • Deleting read-only files: If a file is marked as read-only, your script won't have the authority to delete it, which also results in a PermissionError. To get around this, you first need to change the file's permissions. You can use the os.chmod() function to grant write access before you call os.remove().
  • Avoiding race conditions: A race condition can occur when you check for a file's existence and then delete it. Another process might remove the file between your os.path.exists() check and your os.remove() call, causing an unexpected FileNotFoundError. Because of this, wrapping the deletion in a try...except block is often a safer and more atomic approach than checking first.

Handling files that are still open when using os.remove()

One of the most common errors you'll face is trying to delete a file that your script still has open. On operating systems like Windows, this action often triggers a PermissionError because the file is locked. The following code demonstrates this exact scenario.

import os

# Create and open a file
file_path = "data.txt"
file = open(file_path, "w")
file.write("Some data")

# Try to delete while still open
os.remove(file_path) # This will raise an error on Windows
print(f"File '{file_path}' has been deleted")

The script opens data.txt but never closes the file handle. When os.remove() is called, the file remains locked by the program, which causes the deletion to fail. See how to fix this in the next example.

import os

# Create and open a file
file_path = "data.txt"
file = open(file_path, "w")
file.write("Some data")

# Close the file before deleting
file.close()
os.remove(file_path)
print(f"File '{file_path}' has been deleted")

The fix is to call file.close() before attempting deletion with os.remove(). This simple step releases the file lock, preventing the PermissionError that occurs when trying to delete an open file. Always ensure files are closed after you're done with them, especially in programs that manage many files at once. Using a with statement, as shown in earlier examples, is the most reliable way to handle this automatically and avoid the issue entirely.

Deleting read-only files with proper permissions

Another common hurdle is trying to delete a file that's been marked as read-only. Your script won't have the necessary permissions, leading to a PermissionError. The code below demonstrates what happens when you try to remove a protected file.

import os
import stat

# Create a file and make it read-only
file_path = "readonly.txt"
with open(file_path, "w") as f:
f.write("Protected content")

os.chmod(file_path, stat.S_IREAD) # Make file read-only

# Try to delete the read-only file
os.remove(file_path) # Will fail on some systems
print(f"File '{file_path}' has been deleted")

The script uses os.chmod() with stat.S_IREAD to make the file read-only. This removes the write permissions needed for deletion, causing os.remove() to fail. The following code demonstrates how to correctly manage permissions before deletion.

import os
import stat

# Create a file and make it read-only
file_path = "readonly.txt"
with open(file_path, "w") as f:
f.write("Protected content")

os.chmod(file_path, stat.S_IREAD) # Make file read-only

# Change permissions before deleting
os.chmod(file_path, stat.S_IWRITE | stat.S_IREAD)
os.remove(file_path)
print(f"File '{file_path}' has been deleted")

The fix is to restore write permissions before you try to delete the file. This allows os.remove() to execute without a PermissionError.

  • Use os.chmod() to add write access back, combining stat.S_IWRITE with the existing read permission using the | operator.
  • Once permissions are updated, the file can be deleted successfully.

This is a crucial step when managing files your script doesn't own or those with default system restrictions.

Avoiding race conditions with os.path.exists() checks

A race condition occurs when your script's timing conflicts with another process. While checking if a file exists with os.path.exists() before deleting it seems logical, another program could remove the file in that brief gap, causing an unexpected error.

The code below demonstrates this vulnerable pattern, where the check and the action are separate steps, creating a chance for failure.

import os

file_path = "shared_file.txt"

# This approach can lead to race conditions
if os.path.exists(file_path):
# Another process might delete the file here before we do
os.remove(file_path)
print(f"File '{file_path}' has been deleted")
else:
print(f"The file '{file_path}' does not exist")

The time between checking for the file with os.path.exists() and deleting it with os.remove() creates a small window for failure. Another process could remove the file first, causing an unexpected error. The code below demonstrates a safer way.

import os

file_path = "shared_file.txt"

# Use try-except to handle the file deletion atomically
try:
os.remove(file_path)
print(f"File '{file_path}' has been deleted")
except FileNotFoundError:
print(f"The file '{file_path}' does not exist")

A safer approach is to wrap the os.remove() call directly in a try...except block. This treats the deletion as a single, atomic operation. If another process removes the file first, your code simply catches the FileNotFoundError and moves on without crashing.

  • This method is more robust than checking first, especially in multi-threaded applications or scripts where other programs might interact with the same files.

Real-world applications

Now that you've mastered the challenges of file deletion, you can apply these skills to practical tasks like automated cleanup and building a recycling bin.

Deleting files based on modification time with os.path.getmtime()

A common maintenance task is deleting old files, and you can accomplish this by checking each file's last modification time with os.path.getmtime().

import os
import time

# Create a test directory with an old file
os.makedirs("logs", exist_ok=True)
with open("logs/old_log.txt", "w") as f:
f.write("Old log content")
os.utime("logs/old_log.txt", (time.time() - 30*86400, time.time() - 30*86400))

# Delete files older than 14 days
for file in os.listdir("logs"):
path = os.path.join("logs", file)
if time.time() - os.path.getmtime(path) > 14*86400:
os.remove(path)
print(f"Deleted old file: {path}")

This script automates cleaning up old files from a directory. It first creates a sample log file and uses os.utime() to artificially set its modification date to 30 days in the past, making it easy to test the deletion logic.

  • The code then iterates through the logs directory to check each file.
  • It calculates a file's age by subtracting its last modification time, retrieved with os.path.getmtime(), from the current time.
  • If any file is older than 14 days, it's permanently deleted with os.remove().

Implementing a recycling bin with shutil.move()

Instead of permanently deleting files, you can create a safer "recycling bin" by moving them to a designated folder with shutil.move().

import os
import shutil

# Setup recycle bin and test file
os.makedirs("recycle_bin", exist_ok=True)
with open("important_doc.txt", "w") as f:
f.write("Important content")

# Move to recycle bin instead of deleting
if os.path.exists("important_doc.txt"):
shutil.move("important_doc.txt", "recycle_bin/important_doc.txt")
print("File moved to recycle bin instead of being deleted")
print(f"Files in recycle bin: {os.listdir('recycle_bin')}")

You can avoid permanent data loss by moving files to a temporary holding area. This script demonstrates the concept using shutil.move() to relocate important_doc.txt into a folder named recycle_bin. It's a practical way to build a recovery feature into your applications.

  • First, os.makedirs() with exist_ok=True ensures the destination folder is ready without causing an error if it's already there.
  • Then, shutil.move() transfers the file, providing a reversible alternative to outright deletion.

Get started with Replit

Turn what you've learned into a real tool with Replit Agent. Describe what you want, like “a script to delete log files older than 30 days” or “a tool to find and remove all temporary files.”

The agent writes the code, tests for errors, and deploys your app. Start building with Replit and bring your ideas to life.

Get started free

Create and deploy websites, automations, internal tools, data pipelines and more in any programming language without setup, downloads or extra tools. All in a single cloud workspace with AI built in.

Get started for free

Create & deploy websites, automations, internal tools, data pipelines and more in any programming language without setup, downloads or extra tools. All in a single cloud workspace with AI built in.