Skip to content
  • (+91) 9409548155
  • support@appdividend.com
  • Home
  • Pricing
  • Instructor
  • Tutorials
    • Laravel
    • Python
    • React
    • Javascript
    • Angular
  • Become A Tutor
  • About Us
  • Contact Us
Menu
  • Home
  • Pricing
  • Instructor
  • Tutorials
    • Laravel
    • Python
    • React
    • Javascript
    • Angular
  • Become A Tutor
  • About Us
  • Contact Us
  • Home
  • Pricing
  • Instructor
  • Tutorials
    • Laravel
    • Python
    • React
    • Javascript
    • Angular
  • Become A Tutor
  • About Us
  • Contact Us
Python

How to Delete File If It Exists in Python

  • 08 Jun, 2025
  • Com 0
Deleting a file if it exists in Python

Our primary goal is to remove a file if it exists; if it does not, we need to avoid the error.

Here are five ways in Python:

  1. Using os.remove() along with os.path.exists()
  2. Using send2trash (Soft delete)
  3. Using os.unlink()
  4. Using pathlib.Path.unlink()
  5. Using shutil.rmtree() (For removing a directory)

Method 1: Using os.remove() along with os.path.exists()

The os.remove() method is a built-in Python method that removes a file from the system. However, it raises a FileNotFoundError if the file does not exist.

For checking file existence, we can use the os.path.exists() method before executing the os.remove() method. That way, we are adding one layer before removal to avoid the program crashing.

Let’s say we have a file called app.cpp in our current working directory.

app.cpp file in the file system

We will remove the app.cpp file using the code below:

import os

if os.path.exists("app.cpp"):
    os.remove("app.cpp")
    print("The file has been deleted successfully")
else:
    print("The file does not exist!")

# Output: The file has been deleted successfully

file has been removed

If you try to execute the above script again, you will get the following output.

The file does not exist!

Before removing the file, it checks if it exists; in our case, it does not. So, it returns the “File does not exist!” output.

If the file exists but lacks write permissions, the os.remove() function raises a PermissionError.

Use try-except when deleting multiple files in a loop to avoid repetitive existence checks, improving performance.

Method 2: Using send2trash

There is a third-party library called send2trash that you can use to soft delete the files instead of permanently deleting them. It uses the trash/recycle-bin instead.

Let’s say we have a folder named “docs” and inside that, we need to delete all the files that have an extension .log.

So, there may be multiple files to delete. For each ‘.log’ file found, it prints its path and uses ‘send2trash’ to move it to the system trash, avoiding permanent deletion.

Here is the screenshot of the “docs” folder:

3 log files screenshot

In the above screenshot, you can see that there are 3 log files. We will delete those 3 log files based on the .log extension.

Install the send2trash library if you have not already installed the command below:

pip install send2trash

With the help of the pathlib module, we can use the Path().rglob() method to find the .log files.

from pathlib import Path
from send2trash import send2trash

log_files = Path('docs').rglob('*.log')

for file_path in log_files:
    try:
        send2trash(file_path)
        print(f"Deleted: {file_path}")
    except Exception as e:
        print(f"Failed to delete {file_path} — {e}")

# Output:
# Deleted: docs/hello.log
# Deleted: docs/new.log
# Deleted: docs/main.log

From the output, you can see that all three 3 log files have been deleted. Now, let’s verify this in the file system.

3 log files have been soft deleted using send2trash library

If you check the Recycle Bin/Trash, you will see these three files as well, because they do not permanently delete the files from the system.

Method 3: Using os.unlink()

The os.unlink()  method removes a file. It’s identical to the os.remove() method, which is why it’s rarely used.

You can check if the file exists using os.path.isfile() and then use this method to remove a file safely.

I have created an app.cpp file in the current directory again.

app.cpp file in the file system

Here is the code to delete it:

import os

file_path = 'app.cpp'

# Check if the file exists
if os.path.isfile(file_path):
    try:
        os.unlink(file_path)
        print(f"File '{file_path}' has been deleted.")
    except OSError as error:
        print(f"Error: {error} - File '{file_path}' could not be deleted.")
else:
    print(f"File '{file_path}' does not exist.")

# Output: File 'app.cpp' has been deleted.

file has been removed

If the file exists, it will be removed. If it does not, it will execute the except block, which prints “Error while deleting file”.

Method 4: Using pathlib.Path.unlink()

The Path.unlink() method from the pathlib module also removes a file, with the advantage that it can make your code more readable and expressive.

Here is a file before deleting:

screenshot of the file that will be deleted

from pathlib import Path

file_path = Path('app.cpp')

# Check if the file exists
if file_path.is_file():
    try:
        file_path.unlink()
        print(f"File '{file_path}' has been deleted.")
    except OSError as error:
        print(f"Error: {error} - File '{file_path}' could not be deleted.")
else:
    print(f"File '{file_path}' does not exist.")

# Output: File 'app.cpp' has been deleted.

screenshot after deleting a file

Method 5: Using shutil.rmtree()

The shutil.rmtree() function is used to remove a directory and all of its contents, including all subdirectories and files.

If you are looking for a method that can delete a file or directory, you can use this approach. Even if you are unsure whether the path is a file or a directory, shutil.rmtree() can be used for directories, but it’s overkill for single files.

Let’s create an app.cpp file again inside the new_dir directory, and we will remove this directory.

screenshot of a directory

import os
import shutil

dir_path = 'new_dir'

# Check if the directory exists
if os.path.exists(dir_path) and os.path.isdir(dir_path):
    try:
        shutil.rmtree(dir_path)
        print(f"Directory '{dir_path}' has been deleted.")
    except OSError as error:
        print(f"Error: {error} - Directory '{dir_path}' could not be deleted.")
else:
    print(f"Directory '{dir_path}' does not exist.")

# Output: Directory 'new_dir' has been deleted.
# Automatically app.cpp file will be deleted if it exists.

screenshot of the removed directory

You can see that the “new_dir” has been deleted along with the app.cpp file inside it.

That’s all!

Post Views: 12
Share on:
Krunal Lathiya

With a career spanning over eight years in the field of Computer Science, Krunal’s expertise is rooted in a solid foundation of hands-on experience, complemented by a continuous pursuit of knowledge.

How to Convert Char to Int in Python
How to Get File Size in Python (4 Ways)

Leave a Reply Cancel reply

Your email address will not be published. Required fields are marked *

Address: TwinStar, South Block – 1202, 150 Ft Ring Road, Nr. Nana Mauva Circle, Rajkot(360005), Gujarat, India

Call: (+91) 9409548155

Email: support@appdividend.com

Online Platform

  • Pricing
  • Instructors
  • FAQ
  • Refund Policy
  • Support

Links

  • About Us
  • Contact Us
  • Privacy Policy
  • Terms of services

Tutorials

  • Angular
  • React
  • Python
  • Laravel
  • Javascript
Copyright @2024 AppDividend. All Rights Reserved
Appdividend