Delete File in Python
Delete a file from disk using os.remove.
BeginnerFile Handling ProgramsExample 20 of 20
delete-file.py
1# Program to delete a file23import os45filename = input("Enter filename to delete: ")67if os.path.exists(filename):8 os.remove(filename)9 print("Deleted", filename)10else:11 print("File does not exist.")
Output
Enter filename to delete: old.tmp Deleted old.tmp
What's going on
os.path.exists checks for the file first to avoid raising an exception when calling os.remove.
After this program
If the idea is still fuzzy, read Day 14: File Handling in the Python course. For a short check, try the Python quiz (300 questions). Stay with all 20 file handling programs, or see every topic on Python exercises.