Python Delete Files

To delete a file, you can use the os.remove() function from the os module. Always ensure that the file exists before attempting to delete it.

Example: Deleting a File

# Deleting a file
import os
if os.path.exists('example.txt'):
    os.remove('example.txt')
    print('File deleted successfully.')
else:
    print('File does not exist.')

Output

File deleted successfully.

Explanation: This example checks if the file example.txt exists before attempting to delete it using the os.remove() method. If the file does not exist, it will print an error message.