How To Delete Files in Python

Delete A File In Python

Introduction

In our Python file handling Tutorial, we learned how to manipulate files from within Python. In this tutorial, we’ll learn how to delete files in Python.

We know how to read from and write to a file in Python. Let’s learn the delete operation in Python today.

Suppose after successfully creating a file, we perform some operations on it like reading and writing. As soon as we are done using the file for analyzing different sets of data, maybe in some cases, we don’t need it in the future. At this point how do we delete the file? In this tutorial, we are going to learn that.

Methods to Delete Files in Python

Let us take a look at the different methods using which we can delete files in Python.

1. Using the os module

The os module in Python provides some easy to use methods using which we can delete or remove a file as well as an empty directory. Look at the below-given code carefully:

import os
if os.path.isfile('/Users/test/new_file.txt'):
    os.remove('/Users/test/new_file.txt')
    print("success")
else:    
    print("File doesn't exists!")

Here we have used an if-else statement to avoid the exception that may arise if the file directory doesn’t exist. The method isfile() checks the existence of the file with filename- ‘new_file.txt’.

Again, the os module provides us with another method, rmdir(), which can be used to delete or remove an empty directory. For example:

import os
os.rmdir('directory')

Note: The directory must be an empty one. If it contains any content, the method we return an OSerror.

2. Using the shutil module

The shutil is yet another method to delete files in Python that makes it easy for a user to delete a file or its complete directory(including all its contents).

rmtree() is a method under the shutil module which removes a directory and its contents in a recursive manner. Let us see how to use it:

import shutil
shutil.rmtree('/test/')

For the above-mentioned code, the directory ‘/test/’ is removed. And most importantly, all the contents inside the directory are also deleted.

3. Using the pathlib module

pathlib is a built-in python module available for Python 3.4+. We can remove a file or an empty directory using this pre-defined module.

Let’s go for an example:

import pathlib
file=pathlib.path("test/new_file.txt")
file.unlink()

In the above example, the path() method is used to retrieve the file path whereas, the unlink() method is used to unlink or remove the file for the specified path.

The unlink() method works for files. If a directory is specified, an OSError is raised. To remove a directory, we can resort to one of the previously discussed methods.

References