Remove or Delete File - Python os.remove() - Examples


Python - Delete File

To remove or delete a file using Python, call remove() method of os library with the path to the file passed as argument to the remove function.

In this tutorial, we shall learn how to delete a file, and different scenarios that we may encounter while deleting a file, like file not present, etc.

Syntax of os.remove()

Following is the syntax of remove() function.

os.remove('filepath')

If the file is present, remove() function deletes the file. But, if the file is not present, remove() function throws FileNotFoundError.

So, if you do not know if the file is present or not, and would not like to end up with FileNotFoundError at occasions, you may first check if the file is present and continue with the file removal process.

Examples

1. Remove given File

Following is an example to remove a file named data.txt present at the location same as that of the program.

Python Program

import os

os.remove('data.txt')
print('The file is removed.')

If your file is located somewhere else, other than your current directory, provide the full path (absolute path).

Python Program

import os

os.remove('C:\workspace\python\data.txt')
print('The file is removed.')
Python Remove or Delete File - os.remove()

The file is successfully removed.

2. Try to remove a File that is not present

If the file specified by the provided path is not present, you will get FileNotFoundError error.

Python Program

import os

os.remove('C:\workspace\python\aslkdjfa.txt')
print('The file is removed.')

Output

FileNotFoundError: [WinError 2] The system cannot find the file specified: 'aslkdjfa.txt'

Summary

In this tutorial of Python Examples, we learned how to delete or remove a file using os Python library.