How to delete a file in Python

problem

You wish to delete one or more files with Python. In this post we will see how to do that using the os library.

SOLUTION

We import the os library that gives us functions from the Operating System. More specifically,  deleting a file is an action the OS performs.

EXAMPLE 1 - SINGLE FILE DELETION

Let’s assume the file to delete is named “test.txt” and it’s in the same directory with the Python program as shown in the screenshot below:

Python delete file example

The file is empty (0 bytes) as it’s for demonstration purposes.

Did you know?

On a Unix OS, we can quickly create an empty file by using the touch command in the terminal.
>> touch test.txt

To delete it we will use the os.remove() function and pass the filename as an argument. For example:

delete_file.py
				
					import os

filename = "test.txt"

os.remove(filename)

				
			
running
				
					python3 delete_file.py
				
			
output
Python delete file deleted example

File deleted!

EXAMPLE 2 - FILE DOES NOT EXIST

What if the file we specified does not exist or we mistyped its filetitle?

Let’s rerun the code above for the second time; without the file existing. The file has been deleted already, so let’s observe the result.

output

It’s crashing with a FileNotFoundError as shown in the screenshot below:

Python filenotfound error occurred on delete file example

In order to fix our code and avoid it from crashing we need to add some safe guard code. In this case, error handling. 

Instead of directly calling the os.remove() function, we first try to delete it and if it fails then we catch the failing error/ exception.

ADDING TRY-CATCH STATEMENT
delete_file.py
				
					import os

filename = "test.txt"

try:
   os.remove(filename)
except FileNotFoundError:
   print("File not found so it can't be deleted. Check the file exists...")

				
			
running
				
					python3 delete_file.py
				
			
output
Python delete file with try catch example

Now, the program instead of crashing, it’s giving us a user-friendly error message.

At the except statement we’re checking for the case the file is not found. Other cases can include PermissionError.

This happens when we try to delete a file and the permission is denied due to user’s permissions.

EXAMPLE 3 - DELETION OF MULTIPLE FILES

What if we want to delete all files in a directory? In this case, we will need to specify the directory instead of a single filename and follow a simple algorithm like the one as follows.

Steps:

  1. Use the os.listdir() function to list all items in a given directory,  
  2. For each item, use os.path.join() to get its full path by joining the directory’s path and item’s filename
  3. Then check if the item is a file with os.path.isfile() function and if so, remove it, otherwise do nothing because it’s a directory.

 

Implementation:

delete_files.py
				
					import os

directory_path = "./files_to_delete"

list_dir = os.listdir(directory_path)

for item in list_dir:
   item_path = os.path.join(directory_path, item)
   if os.path.isfile(item_path):
       os.remove(item_path)

				
			

The directory I’m using in this example is called “files_to_delete” and has 5 files and 1 directory as shown in the screenshot:

Python delete multiple files example

Also in this case the files and the inner directory are empty.

running
				
					python3 delete_file.py
				
			
output
Python delete multiple files output no error in console

No errors on the console.

Let’s check the directory in the screenshot below:

Python after deleting multiple files example

As expected all 5 files in “files_to_delete” got deleted, but the directory no because we checked that each item had to be a file.

If we modify the code above and remove that if statement, both files and folders will be removed.

DELETING FOLDERS INSTEAD OF FILES

With the same logic we can invert the if logic by adding a not and delete only folders and leave files intact.

For example:

delete_files.py
				
					
if not os.path.isfile(item_path): #check if it's a directory
   os.remove(item_path)

				
			

Because in the filesystem an item is either a file or a folder (directory).

The os.path.isfile() will return True if the argument we pass is a file and False if it’s not, which means it’s a directory.

conclusion

In this post we saw how to use Python’s built-in library os, to delete files, list items in a directory and check if an item is a file or not. Moreover, we saw how to safeguard our program with try-except mechanism to avoid crashing it in case the file cannot be found. 

 

References:

https://docs.python.org/3/library/os.html#module-os

Share it!

Facebook
Twitter
LinkedIn
Reddit
Picture of Ellion

Ellion

Professional IT consultant, writer, programmer enthusiast interested in all sorts of coding.
Eats all cookies 🍪

0 0 votes
Article Rating
Subscribe
Notify of
guest
0 Comments
Oldest
Newest Most Voted
0
Would love your thoughts, please comment.x
()
x
Privacy Overview

This website uses cookies so that we can provide you with the best user experience possible. Cookie information is stored in your browser and performs functions such as recognising you when you return to our website and helping our team to understand which sections of the website you find most interesting and useful.

Strictly Necessary Cookies (Ads)

Strictly Necessary Cookie should be enabled at all times so that we can save your preferences for cookie settings. We use Google Ads on this site.

Google Analytics Cookies

This website uses Google Analytics to collect anonymous information such as the number of visitors to the site, and the most popular pages.

Keeping this cookie enabled helps us to improve our website.

HotJar Cookies

We use Hotjar in order to better understand our users’ needs and to optimize this service and experience. Hotjar is a technology service that helps us better understand our users’ experience (e.g. how much time they spend on which pages, which links they choose to click, what users do and don’t like, etc.) and this enables us to build and maintain our service with user feedback. Hotjar uses cookies and other technologies to collect data on our users’ behavior and their devices. This includes a device's IP address (processed during your session and stored in a de-identified form), device screen size, device type (unique device identifiers), browser information, geographic location (country only), and the preferred language used to display our website. Hotjar stores this information on our behalf in a pseudonymized user profile. Hotjar is contractually forbidden to sell any of the data collected on our behalf.

For further details, please see the ‘about Hotjar’ section of Hotjar’s support site.