In this Python tutorial, you will learn how to delete a file using remove() function of the os module.

Python – Delete File

To delete a file in Python, we can import os package and use remove() function of the os package.

First we shall look into the syntax of os.remove() function. Secondly, we shall look into examples, where we actually delete a file. The examples cover scenarios: delete file without checking if it is actually present; delete file with a prior check if the file is present.

Syntax

The syntax of os.remove() function is:

os.remove(file_path)

os.remove() deletes the file present at the location provided by String value file_path.

os.remove() deletes the file if it is present. If the file is not present, nothing happens, not even an error occurs. The execution continues with subsequent program statements. So, it is recommended that you check if the file is present, if you would like to be sure if you have actually deleted the file.

ADVERTISEMENT

Examples

1. Delete File in Python

In the following Python program, we are deleting a file present at the location D:/data.txt.

Python Program

import os

#delete the file
os.remove("D:/data.txt")

print('The file is deleted.')

Output

The file is deleted.

2. Check if file is present and then delete file

You can make a check if file is present, prior to the deletion and make sure, if you have actually deleted the file.

To check if the file is present, use os.path.isfile() function. os.path.isfile() function returns true if file is present in the storage. Else the function returns false.

Once we are sure that the file is present, then we can call the function os.remove() to delete the file.

Python Program

import os

file_path = "D:/data.txt"

#check if file is present
if(os.path.isfile(file_path)):
	#delete the file
	os.remove(file_path)
	print('The file is deleted.')
else:
	print('The file is not present.')

If the file is present and deleted, you would get the following output.

Output

The file is deleted.

If the file is not present, and you try to delete, you get the following output.

Output

The file is not present.

Conclusion

In this Python Tutorial, we learned how to delete a file programmatically in Python using os.remove() function.