Skip to main content

Python Delete File

The os Python module provides a big range of useful methods to manipulate files and directories.

The os.remove() function is used to remove a file.

Syntax

The syntax of os.remove() is:

os.remove(filename)

where:

  • filename is a string that specifies the file to delete
note

If the filename does not exist, the os.remove() function raises a FileNotFound error.

You can avoid this, correctly handling the error or checking if the file exists

Example: Delete File

For example, delete the file test.txt.

import os 

os.remove('test.txt')

Example: Delete File with Handling Exceptions

To avoid error , you can use try...except statement.

For example, try to delete test.txt file handling the possible error with try...except statement:

import os

try:
os.remove('test.txt')
except FileNotFoundError as e:
print(e)

Example: Delete File only if it exists

To avoid error, you can check if the file exists before deleting it.

For example, try to delete test.txt file only if it exists:

import os

filename = 'test.txt'
if os.path.exists(filename):
os.remove(filename)
note

Note that os.path.exists() method is used to check if a certain file exists. You can learn more in Check If File Exists Chapter