Python remove file - How to delete a file?

The files in Python are used for various purposes by the developers. After the developer has worked with the file, it is important to know how to delete it. For example in a large program, the developer would need to create files to store data but would not require them after the execution of the program. This is when deleting the file is a good idea and in this tutorial, we will discuss different ways to delete or remove a file in Python.
In this tutorial, we will discuss various methods to remove a file in Python using the os.remove() and the pathlib module. We will also discuss how to remove an empty and a non-empty directory in Python.

Table of contents

Removing file in Python using os.remove()

The OS module in Python provides functions for interacting with the operating system. This standard utility module provides a portable way of using operating system-dependent functionality. This module can remove a file or file path but cannot delete a directory. If the specified path is a directory, then the module will raise an OSError.

Syntax:

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

Case 1: To remove a file

Input:

import os

file = 'file.txt'  
location = "/home/User/Documents"
path = os.path.join(location, file)  
os.remove(path)

print (“The file has been removed")

Output:

The file has been removed

In the above code snippet, we first specify which file we want to delete and where it's located. Then, after joining, we use the os.remove() operation to delete it.

Case 2: The specified path is a directory

Input:

import os

path = "/home/User/Documents/abcdef"

os.remove(path)
print (“The file has been removed")

Output:

Traceback (most recent call last):
  File "osremove.py", line 15, in 
    os.remove(path)
IsADirectoryError: [Errno 21] Is a directory: '/home/User/Documents/acdef'

Here, we do not need to use the 'join' operation as we directly specify the exact location. Make sure to import the OS library before using the os.remove() function.

Using the pathlib module to remove a file in Python

The pathlib module is very useful in removing or deleting a file in Python 3.4 or above. It is similar to the os.remove() and have to create a path object at first.

Input:

import pathlib
p_obj = Path(".")
type(p_obj)
file = pathlib.Path("file_1/file.txt")
file.unlink()

When an instance of the Path class is created, a WindowsPath or PosixPath will be returned according to the machine you’re working on. And the unlink() function is used to remove the file or the symbolic link.

Removing empty directory

The above two approaches cannot be used to remove a folder. The os.rmdir() function in the OS module can delete an empty directory in Python.

Input:

import os
directory = "/home/User/Documents/abcdef"
os.rmdir('directory')

print (“The directory is removed.”)

Output:

The directory is removed.

The os.rmdir() function can only be used to delete an empty directory. If you specify a folder that contains files, the following error will be returned.

Input:

import os

directory = "/home/User/Documents/abcdef/ghi"

os.rmdir('directory')

Output:

Permission denied: '/home/User/Documents/abcdef/ghi' Directory 'ghi' can not be removed

Removing a non-empty directory

You can use the high-level file operation module, shutil to remove a file or collection of files. You can use this module in the same way as the os.rmdir() function but here you can also remove the non-empty directories. All the contents inside the directory are removed as well.

Input:

import shutil
path = /home/User/Documents/abcdef
shutil.rmtree('path')

print (“All the files inside the directory are removed with the directory”)

Output:

All the files inside the directory are removed with the directory

Just remember that you cannot remove a single file with the shutil.rmtree() function. For deleting a single file, you can use the os.remove() function and the pathlib module that's been illustrated above.

Closing thoughts

In Python, removing a file is a very common operation. The os.remove() function and the pathlib module can remove a single file. While the os.rmdir() function removes an empty directory and the shutil module removes the non-empty directory in Python. You can learn other Python concepts here.