Delete File in Python
Delete a file from disk using os.remove.
BeginnerFile Handling ProgramsExample 20 of 20
delete-file.py
Run in browser1# 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.