Python Delete File

Created with Sketch.

Python Delete File

Summary: in this tutorial, you’ll learn how to delete a file from Python using the os.remove() function.

To delete a file, you use the remove() function of the 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.

Leave a Reply

Your email address will not be published. Required fields are marked *