How to delete a file in Python with examples

In order to delete a file using a Python program, you have to import the os module. In this tutorial, you will learn how to delete a file in Python with some easy examples. The function we are going to use to delete a file from a directory is os.remove()

Here we are going to show you how to delete a file from a directory with an easy example.

We have a text file in our directory. The file name of the text file is: this_is_file.txt

( The os.remove() function can delete any type of file, this is not necessary to be a text file )

Now we are going to write a Python program in the same directory to delete the file.

import os
os.remove('this_is_file.txt')

If we run this program, this_is_file.txt will be deleted from the directory.

If your file is located in other sub-directory then you can simply put the path instead of the file name to delete the file with the directory.

import os

file = 'this_is_file.txt'

location = "/public/files"

path = os.path.join(location, file)

os.remove('path')

You can use both single quote and double quote to surround the path of the file.

os.remove in Python

Return Type: It does not return any value.

Parameter: Path of the file is to be passed as a parameter surrounded by single quotes or double quotes.

os.rmdir in Python to delete an entire directory

import os
os.rmdir('directory')

Return Type: It does not return any value.

Parameter: Directory or directory path is to be passed as a parameter surrounded by single quotes or double quotes.

Special note:

It will only delete an empty directory.

To delete an entire directory with all of its contents you have to use the following:

 shutil.rmtree(mydir)

Leave a Reply

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