How to delete a file in Python with examples

In this tutorial, we will learn how to delete a file in Python.

We will be using the below methods:

  • os.remove
  • os.unlink

Using os.remove to delete a file from a directory in Python

Let’s take an example:

os.remove in python

You can see that I have a file named myFile.txt in a directory and in the same directory I have my Python program file.

import os 
os.remove('myFile.txt')

If you run this program it will delete the file from the directory.

You just need to put the file path location in the argument of the os.remove() function.

We can also use double quote instead of small quotes to wrap the file path just like this:

os.remove("myFile.txt")

Using os.unlink to delete a file

We can also delete a file just like the previous method. But this time we are going to use os.unlink().

Take a look at the below example:

import os 
os.unlink("myFile.txt")

This will also delete the file.

Delete a file if the file exists using Python

If you want your program to look for the filename and if it exists then only it will attempt to delete that file, then you can use if else statement.

import os 
if os.path.exists("myFile.txt"):
  os.unlink("myFile.txt")
else:
  print("No such file found")

If you run this it will only try and delete the file if it exists. Otherwise, it will jump to the else: part.

Recommended article:

How to delete a directory tree in Python using shutil.rmtree()

Leave a Reply

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