Delete File
Delete a file from disk using os.remove.
BeginnerTopic: File Handling Programs
Python Delete File Program
This program helps you to learn the fundamental structure and syntax of Python programming.
# Program to delete a file
import os
filename = input("Enter filename to delete: ")
if os.path.exists(filename):
os.remove(filename)
print("Deleted", filename)
else:
print("File does not exist.")Output
Enter filename to delete: old.tmp Deleted old.tmp
Understanding Delete File
os.path.exists checks for the file first to avoid raising an exception when calling os.remove.
Note: To write and run Python programs, you need to set up the local environment on your computer. Refer to the complete article Setting up Python Development Environment. If you do not want to set up the local environment on your computer, you can also use online IDE to write and run your Python programs.