Skip to content

Python Delete File

How to delete a file in Python using os.remove() with proper error handling or existence checks to avoid FileNotFoundError.

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

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)
Navigation