Thuta Learning
IntermediateProgrammingbeginner

Python Delete Files

Relax. We'll talk through this in plain words — no textbook voice.

To delete files, we use Python's os module. os.path.exists() lets you check whether the file exists first.

python
import os

file_to_delete = "dummy_file.txt"
with open(file_to_delete, "w") as f:
    f.write("Temp file.")

print(f"'{file_to_delete}' created.")

if os.path.exists(file_to_delete):
    os.remove(file_to_delete)
    print(f"'{file_to_delete}' has been deleted.")
You should see
'dummy_file.txt' created. 'dummy_file.txt' has been deleted.
Python Delete Files | Thuta Learning