To delete file in python, you have to import os library and use os.remove() function to remove the desired file given by the user as shown in the program given below.
Following python program ask from user to enter the name of the file and then delete that file using the function os.remove(). But before performing the deletion operation using the code given below, let's first see the files present inside the folder with this snapshot. Snapshot before file delete:
Now let's see the python code to delete file:
# Python Program - Delete File import os while True: print("Enter 'x' for exit.") filename = input("Enter name of file to delete: ") if filename == 'x': break else: print("Removing the file....") os.remove(filename) print("File,",filename,"successfully deleted!!\n")
Here is the sample run of the above python program illustrating how to delete file:
Now, let's again see the list of files present in the same folder with this snapshot. You will see that the given file to perform deletion operation from the above python program shouldn't exist. Snapshot after file delete:
You may also like to learn or practice the same program in other popular programming languages: