How to Delete a File in Python?

Ayushi Trivedi Last Updated : 13 Jun, 2024
5 min read

Introduction

This article offers a thorough tutorial on how to delete files in Python using a variety of modules and approaches. It goes over simple techniques like using os.remove() and os.unlink(), more complex techniques like pathlib.Path.unlink() and shutil.rmtree() for directories, and safer options like send2trash for putting files in the recycling bin. It also describes how to use tempfile to manage temporary files and how to deal with symbolic links. In this article we will explore the methods to delete a file in Python.

Overview

  • Gain knowledge of fundamental file deletion methods in Python using os.remove() and os.unlink().
  • Learn how to delete entire directories and their contents recursively with shutil.rmtree().
  • Understand the process of deleting symbolic links using os.unlink().
  • Employ pathlib.Path.unlink() for a modern and readable approach to file deletion.
  • Use send2trash to safely delete files by sending them to the recycle bin, allowing for recovery if needed.
  • Create and automatically delete temporary files using the tempfile module.
Delete a file in python

Using os.remove()

os.remove() is a method of Python to permanently delete a file from the filesystem. It requires importing the os module and providing the file path. To avoid exceptions, check if the file exists using os.path.exists(). If it does, os.remove(file_path) will delete it, with a confirmation message.

import os

# Specify the file name
file_path = 'example.txt'

# Check if the file exists before attempting to delete it
if os.path.exists(file_path):
    # Delete the file
    os.remove(file_path)
    print(f"{file_path} has been deleted successfully.")
else:
    print(f"{file_path} does not exist.")

Explanation:

Use the os.path.exists(file_path) function to determine whether a file is there at the specified path. If the file already exists, Python removes it using os.remove(file_path). If the file is missing, it prints a notification indicating its absence.

Considerations:

  • This procedure raises an exception if file not found. Therefore, it’s wise to verify that a file exists before attempting to remove it.
  • You can use this method when you wish to permanently delete a file.

Using os.unlink() in python you can permanently delete a file from filesystem. The first step is to import the OS module. And then existence of the file must be verified using os.path.exists(). After locating the file, os.unlink(file_path) deletes it and displays a confirmation message.

import os

# Specify the file name
file_path = 'example.txt'

if os.path.exists(file_path):
    # Delete the file
    os.unlink(file_path)
    print(f"{file_path} has been deleted successfully.")
else:
    print(f"{file_path} does not exist.")

Explanation:

  • The os.unlink(file_path) function deletes the file specified by file_path.
  • Like os.remove(), it raises an exception if the file does not exist.

Considerations:

  • os.unlink() and os.remove() are functionally identical for deleting files.
  • Use this method interchangeably with os.remove() depending on your preference or coding style.

Using shutil.rmtree()

In Python, a directory and its contents can be recursively deleted using the shutil.rmtree() method. It is employed to eliminate files, subdirectories, and directories. Make that the directory exists before using it by running os.path.exists(directory_path). Although strong, take it with caution.

import shutil

# Specify the directory path
directory_path = 'example_directory'

if os.path.exists(directory_path):
    # Delete the directory and its contents
    shutil.rmtree(directory_path)
    print(f"{directory_path} has been deleted successfully.")
else:
    print(f"{directory_path} does not exist.")

Explanation:

  • The shutil.rmtree(directory_path) function deletes the directory specified by directory_path and all its contents.
  • It raises an exception if the directory does not exist.

Considerations:

  • Be careful with shutil.rmtree() as it deletes files and directories permanently.
  • Use this method when you want to delete a directory and all its contents recursively.

Using `os.unlink()` in Python removes symbolic links without affecting the target file or directory. This module also check if the symbolic link exists before deleting it. This method is useful for managing symbolic links separately from regular files, ensuring only the link is removed.

import os

# Specify the symbolic link path
symbolic_link_path = 'example_link'

# Check if the symbolic link exists before attempting to delete it
if os.path.exists(symbolic_link_path):
    # Delete the symbolic link
    os.unlink(symbolic_link_path)
    print(f"{symbolic_link_path} has been deleted successfully.")
else:
    print(f"{symbolic_link_path} does not exist.")

Explanation:

  • The os.unlink(symbolic_link_path) function deletes the symbolic link specified by symbolic_link_path.
  • It raises an exception if the symbolic link does not exist.

Considerations:

  • Use this method when you want to delete a symbolic link.

`pathlib.Path.unlink()` in Python offers a modern, intuitive method for deleting files. To construct a Path object for the selected file, it imports thePathclass. The unlink() method removes the file if it is present.

from pathlib import Path

# Specify the file path
file_path = Path('example.txt')

# Check if the file exists before attempting to delete it
if file_path.exists():
    # Delete the file
    file_path.unlink()
    print(f"{file_path} has been deleted successfully.")
else:
    print(f"{file_path} does not exist.")

Explanation:

  • Path(file_path) creates a Path object for the specified file path.
  • file_path.exists() checks if the file exists.
  • file_path.unlink() deletes the file.

Considerations:

  • pathlib provides a more modern and readable way to handle filesystem paths compared to os.

Using send2trash

Sending files to the trash or recycle bin is a safer alternative to using Python’s send2trash function to erase them entirely. Install the module, import the function, and confirm that it exists before submitting the file.

pip install send2trash
from send2trash import send2trash

# Specify the file path
file_path = 'example.txt'

# Check if the file exists before attempting to delete it
if os.path.exists(file_path):
    # Send the file to the trash
    send2trash(file_path)
    print(f"{file_path} has been sent to the trash.")
else:
    print(f"{file_path} does not exist.")

Explanation:

  • send2trash(file_path) sends the specified file to the trash/recycle bin.

Considerations:

  • When you wish to remove files in a safer way that nevertheless permits recovery from the trash, use this procedure.

Using tempfile

The tempfile module in Python allows you to create temporary files and directories that are automatically cleaned up after use. Thus making them useful for short-term data storage during testing or non-permanent data work, and preventing clutter.

import tempfile

# Create a temporary file
temp_file = tempfile.NamedTemporaryFile(delete=True)

# Write data to the temporary file
temp_file.write(b'This is some temporary data.')
temp_file.seek(0)

# Read the data back
print(temp_file.read())

# Close the temporary file (it gets deleted automatically)
temp_file.close()

Explanation:

  • A temporary file created by tempfile.NamedTemporaryFile(delete=True) will be removed upon closure.
  • Like any other file, you can write to and read from the temporary file.
  • The temporary file is automatically erased upon calling temp_file.close().

Considerations:

  • Use this method for temporary files that require automatic deletion after use.

Conclusion

There are several ways to delete files in Python. Simple techniques for permanently removing files are provided via the ‘os.remove()’ and ‘os.unlink()’ routines. Entire directories can be managed using the “shutil.rmtree()” function. ‘os.unlink()’ eliminates symbolic links without compromising the intended outcome. An object-oriented, contemporary method is ‘pathlib.Path.unlink()’.Files are sent to the recycling bin using “send2trash” so they can be recovered. Temporary files are automatically managed by “tempfile.” In this article we explored different methods in python to delete a file.

Frequently Asked Questions

Q1. What is the easiest way to delete a file in Python?

A. You can accomplish file deletion most easily with os.remove() or os.unlink().

Q2. How can I check if a file exists before deleting it?

A. Before deleting a file, use os.path.exists(file_path) to make sure it is there.

Q3. How do I manage temporary files in Python?

A. To generate temporary files that are automatically erased when they are closed, use the tempfile module.

My name is Ayushi Trivedi. I am a B. Tech graduate. I have 3 years of experience working as an educator and content editor. I have worked with various python libraries, like numpy, pandas, seaborn, matplotlib, scikit, imblearn, linear regression and many more. I am also an author. My first book named #turning25 has been published and is available on amazon and flipkart. Here, I am technical content editor at Analytics Vidhya. I feel proud and happy to be AVian. I have a great team to work with. I love building the bridge between the technology and the learner.

Responses From Readers

Clear

Congratulations, You Did It!
Well Done on Completing Your Learning Journey. Stay curious and keep exploring!

We use cookies essential for this site to function well. Please click to help us improve its usefulness with additional cookies. Learn about our use of cookies in our Privacy Policy & Cookies Policy.

Show details