How To Delete File In Python?

Python is a feature-rich programming language that provides different ways for different tasks. Python can be used to delete file or files by using different modules like “os” module etc. In this tutorial, we examine how to remove or delete file or files in Python.

Delete File with os.remove() Method

The most popular and well-known way to remove or delete a file with Python is using the os.remove() method. The remove() method is provided via the “os” module and so the “os” module should be imported to use it. In the following example, we remove the file named “data.txt”.

import os

os.remove("data.txt")

Alternatively, we can use the remove() method in order to remove a file with its complete or absolute path information. In the following example, we remove the file “data.txt” which is located under “/home/ismail/”.

import os

os.remove("/home/ismail/data.txt")

Check If File Exists

There is a helpful method while deleting files. We can use exists() method in order to check if the specified file exists and delete it accordingly.

import os

if os.path.exists("data.txt"):
   os.remove("data.txt")
else:
   print("data.txt does not exist")

Delete File with os.unlink() Method

Another way to remove a file with Python is the unlink() method. The unlink() method is provided with the os module. The unlink() method simply deletes the link between data and file descriptor in the file system. This action is the same as removing the file.

import os

os.unlink("data.txt")

By using the complete path for the Linux it can be expressed like below.

import os

os.unlink("/home/ismail/data.txt")

If the operating system is Windows the unlink() method can be used with a full path like below.

import os

os.unlink("c:\\users\\ismail\\data.txt")

Delete File with shutil.rmtree() Method

Python provides the shutils module where the rmtree() method can be used to delete files. Actually, the rmtree() method can delete specified paths or directories and all of their contents which can be files or folders. But we can use the rmtree() method to delete files.

import shutils

shutils.rmtree("data.txt")

Delete File with pathlib Library

The pathlib module is provided with Python 3.4 and later versions. It provides file system-related methods where the unlink() method can be used to remove or delete a file. First, a path is specified and a path object is created with the Path() constructer and then using this path object unlink() is called with the file name. In the following example, we delete the file “data.txt” located “/home/ismail”.

import pathlib

p = pathlib.Path("/home/ismail")

p.unlink("data.txt")

Leave a Comment