Skip to main content
How To Delete File If Exists In Python

Deleting a File If It Exists in Python

In this article, we’ll learn how to delete a file if it exists using Python. We’ll explore the use of use os.remove() and os.unlink method to remove a file if it’s the only one that exists at the specified location.

Python’s OS module contains functions for interfacing with the operating system.

We’ll check the following conditions before deleting the file:

  • The file doesn’t exist at the given path.
  • The user does not have access to the file at the specified location.
  • The given path is a directory, not a file.

We’ll cover the following Python methods here:

  • Checking if a file exists using os.path.exists().
  • Removing a file using the os.remove() method.
  • Deleting a file using the os.remove() method.
  • Removing a file using os.unlink().

Python Delete file if it exists

We use the os.path.exists() and os.remove() methods in Python to delete a file if it already exists. Let’s use os.path.exists() function before performing the os.remove() method to avoid an error when deleting a file.

Delete File Using os.remove() Method

To remove a file if it exists in Python, we use os.remove(). Ensure you import the OS module at the beginning of the file to use it.

The syntax:
os.remove(path_of_file)

The file path is passed as an argument to the above function, which deletes the file at that path. The file path can be relative to the current working directory or absolute. If the given path doesn’t exist, os.remove() will raise an OSError.

import os
filePath = 'test.txt';

if os.path.exists(filePath):
    os.remove(filePath)
	print("Successfully! The File has been removed")
else:
    print("Can not delete the file as it doesn't exists")

Output:

Successfully! The file has been removed

Delete File Using os.unlink() Method

The os.unlink() method is used to remove or delete a file from the file system.

The Syntax:

os.unlink(filePath)

The above method will have filePath as a parameter. It’s a Path object instead of a string.

Let’s delete a file using the os.unlink() method.

import os 
# Handle errors while calling os.unlink()
try:
    os.unlink(filePath)
	print(File path has been removed successfully);
except:
    print("Error while deleting file ", filePath)

Output:

File path has been removed successfully

Conclusion:

We have explored common Python methods for deleting files from a directory, including os.remove() and os.unlink(). Always ensure the file exists using os.path.exists() before attempting removal. Choose the method that suits your project requirements.

2 thoughts to “Deleting a File If It Exists in Python”

Leave a Reply

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