Delete File in Python

Delete a file from disk using os.remove.

BeginnerFile Handling ProgramsExample 20 of 20
delete-file.py
Run in browser
1# Program to delete a file
2
3import os
4
5filename = input("Enter filename to delete: ")
6
7if 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.