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; print("Enter 'x' for exit."); filename = input("Enter name of file to delete: "); if filename == 'x': exit(); else: print("\nRemoving the file...."); os.remove(filename); print("\nFile,",filename,"successfully deleted!!");
Here is the sample run of the above python program illustrating how to delete file:
Now enter any file name to delete that file say codescracker.txt and press enter key to remove the file from the current directory as shown below:
Now to confirm whether the above file that is codescracker.txt is successfully deleted or not, then 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:
As you can see from the above screenshot, the file codescracker.txt is not present inside the directory as the file is deleted earlier with the help of above program.
Program Video with Compile and Run
You may also like to learn or practice the same program in other popular programming languages: