Summary: In this tutorial, you’ll learn how to delete a file from Python using the remove()
function from the os
module.
To delete a file, you use the
function of the remove()
os
built-in module. For example, the following uses the os.remove()
function to delete the readme.txt
file:
import os
os.remove('readme.txt')
Code language: Python (python)
If the readme.txt
file doesn’t exist, the os.remove()
function will issue an error:
FileNotFoundError: [WinError 2] The system cannot find the file specified: 'readme.txt'
Code language: Python (python)
To avoid the error, you can check the file exists before deleting it like this:
import os
filename = 'readme.txt'
if os.path.exists(filename):
os.remove(filename)
Code language: Python (python)
Alternatively, you can use the try...except
statement to catch the exception if the file doesn’t exist:
import os
try:
os.remove('readme.txt')
except FileNotFoundError as e:
print(e)
Code language: Python (python)
Summary #
- Use the os.
remove()
function to delete a file.
Was this tutorial helpful ?