Python: Delete / Remove Files

You can use the os module in Python to delete or remove files. The os module provides the remove() function to delete a file.

Here’s an example of how to delete a file in Python:

import os

filename = 'file.txt'

if os.path.isfile(filename):
os.remove(filename)
print(f'{filename} was deleted successfully.')
else:
print(f'{filename} was not found.')

Explanation:

  • The first line imports the os module.
  • The os.path.isfile() function checks if the specified file exists.
  • If the file exists, the os.remove() function is called to delete the file.
  • If the file does not exist, a message is printed indicating that the file was not found.

It’s important to use the os.path.isfile() function to check if the file exists before trying to delete it. This prevents an error from being raised if the file does not exist.

You can also use the shutil module in Python to delete a directory and all its contents, including subdirectories and files, with the rmtree() function. However, be careful when using this function, as it permanently deletes the specified directory and its contents and cannot be undone.

Leave a Comment