How to Delete File or Folder in Python

Sometimes Python developers need to remove one or more files and folders from their system. Generally, they use commands like rm for this purpose. But sometimes you may need to do this programmatically from an application or website. You can easily do this using a Python script. This way you can also trigger file deletion from your Python application or website, at the click of a button or by firing some other event. There are several simple ways to do this. In this article, we will learn how to delete file or folder in Python.

How to Delete File or Folder in Python

Python provides several modules for file operations. Among them, pathlib, shutil and os are popular ones. We will use them for our purpose. Here are different ways to remove files and folders in Python.

1. Using pathlib.Path.unlink()

If you are using Python 3.4 and above, then you can use pathlib module to remove files and folders in Python. pathlib is a library that provides a class-based interface to work with file and folder paths in Python. It provides different functions to perform different kinds of tasks. You can use unlink() function to easily remove file. You just need to pass the path of file to be deleted, as a string. Here is the command to remove file /home/ubuntu/data.txt

import pathlib
pathlib.Path.unlink('/home/ubuntu/data.txt')

The unlink() function works with both files as well as symbolic links. If you pass path to a symbolic link, it will delete the symbolic link itself.

2. Using pathlib.Path.rmdir()

If you want to remove an empty directory or folder in Python, then you can use rmdir() function for this purpose. Here is its syntax.

pathlib.Path.rmdir(folder_path)

Here is the command to delete the directory /home/ubuntu/data. Please note, it must be empty.

pathlib.Path.rmdir('/home/ubuntu/data')

3. Using shutil.rmtree()

shutil is another Python library that offers many high-level functions to easily work with files and directories. You can use it in case you are using Python < 3.4. It features rmtree() function that allows you to easily delete a directory tree. Here is its syntax.

shutil.rmtree(path, ignore_errors=False, onerror=None, *, onexc=None, dir_fd=None)

You just need to pass the path to directory. The above command also supports several optional arguments. Among them, ignore_errors, if set to true, then it will ignore any error that occurs during removal of files and folders. If it is set to false, or omitted, then it is handled by error handler specified by onexc or onerror argument.

Here is the command to delete directory tree /home/ubuntu/data.

shutil.rmtree('/home/ubuntu/data')

4. Using os.remove()

OS is another Python library that provides many high level interfaces and functions to interact with underlying OS. It is commonly used to run system commands in Python. It also provides many useful functions for file operations. Among them, you can use os.remove() function to delete a file. Here is the command for it.

import os
os.remove('/home/ubuntu/data.txt')

If the above mentioned file does not exist, then it will raise FileNotFoundError. In fact, on Windows systems, if the file is open, even then you will get an error.

5. Using os.unlink()

If you want to remove a symbolic link, you can use os.unlink() function. Here is its syntax.

os.unlink(path, *, dir_fd = None) 

The file path is the first argument and it is mandatory. The * after that refers to optional arguments. dir_fd is also an optional argument that refers to a directory path. If absolute file path is mentioned as first argument, then this argument is ignored.

Here is the command to remove a symbolic link /home/ubuntu/test.txt.

os.unlink('/home/ubuntu/test.txt')

6. Using os.rmdir()

You can also use os.rmdir() function to remove an empty directory. Its syntax is similar to that of shutil.rmtree().

os.rmdir(path, *, dir_fd = None)  

In the above command, directory path is the first argument, followed by optional arguments. Among them, dir_fd points to a directory path. Its default value is None. It is ignored if absolute directory path is provided in first argument.

Here is the command to delete directory /home/ubuntu/data.

os.rmdir('/home/ubuntu/data')

7. Delete Files with specific extension

Let us look at a common use case where you need to delete all files in a directory with a specific extension. Here is the code to do this.

import os 
from os import listdir

my_path = '/home/ubuntu/data'
for file_name in listdir(my_path):
if file_name.endswith('.txt'):
os.remove(my_path + file_name)

In the above code, we import listdir function to get a list of all files in a directory, as a list. We loop through this list and for each file we call endswith() function to check its extension. We see if the extension is .txt or not. If it is true, then we call os.remove() function on the full file path.

8. Delete All Files in Folder

So far we have seen commands to delete only one file in a directory. What if you need to delete all files in a directory? For this purpose, you can use the following code.

import os, glob

# Loop over files & delete them individually
my_path = "/home/ubuntu/data"
for file in glob.glob(my_path):
os.remove(file)

In the above code, we import glob module to retrieve file and directory paths recursively, as a list. We loop through this list and call os.remove() function on each file.

9. Check if File Exists

Most of the functions we have seen above, require that the file to be deleted, actually exists. However, if the file does not exist, then these functions will throw an Exception. So it is advisable to first check if file exists, before you delete it. For this purpose, you can call os.path.isfile() function. It will accept a file path as argument, and return true if file actually exists at this path. Else it will return false.

import os

my_path = "/home/ubuntu/data.txt"
# File exists
if os.path.isfile(my_path):
os.remove(my_path)
else:
# File does not exist
print("Error: %s file not found" % my_path)

10. Exception Handling

Another solution to use in case the file exists, is to use exception handling. When a file does not exist, most of the above mentioned functions throw an Exception. We can handle this exception to make sure the code continues to run.

import os

# path to file
my_path = '/home/ubuntu/data.txt'

# Delete file
try:
os.remove(my_path)
except OSError as e:
# File does not exist
print("Error: %s - %s." % (e.filename, e.strerror))

In the above code, we call os.remove() function on file path. If the file does not exist at the given path, it throws an exception, which is handled.

Best Practices

There are several best practices you can follow while to delete file or folder.

  1. Make sure the file exists. Otherwise, most of the functions mentioned above will throw an error.
  2. Ensure that the user running these functions has appropriate permissions. Otherwise, you will get an error.
  3. Before deletion, check if file exists using isfile() or some other function. It is a much better way than handling exceptions.

Conclusion

In this article, we have learnt how to delete file or folder in Python. You can use any of them as per your requirement. But please note, the system user that runs these Python functions must have the permission to delete the files & folders. Secondly, these files & folders must actually exist on your disk. Otherwise, you will get an error. Also, most of these commands do not ask for a confirmation before deleting file or directory. Once the file or folder is deleted, there is no way to recover them. So make sure you provide the correct file path as arguments.

Also read:

How to Copy Files in Python
How to Iterate Over Rows in Pandas DataFrame
How to Iterate Over Dictionaries Using Loops

Leave a Reply

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