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 – os.remove()
Following is the syntax of remove() function.
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.
Example 1: Remove File with Python
Following is an example to remove a file named data.txt present at the location same as that of the 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).
import os os.remove('C:\workspace\python\data.txt') print('The file is removed.')
The file is successfully removed.
Example 2: Remove File that is not present
If the file specified by the provided path is not present, you will get FileNotFoundError error.
import os os.remove('C:\workspace\python\aslkdjfa.txt') print('The file is removed.')
FileNotFoundError: [WinError 2] The system cannot find the file specified: 'aslkdjfa.txt'
In this tutorial of Python Examples, we learned how to delete or remove a file using os Python library.