Python Program to Delete File

« Previous Program Next Program »

Delete File in Python

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.

Python Programming Code to Delete File

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:

delete file in python

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':
    print("\nRemoving the file....");
    print("\nFile,",filename,"successfully deleted!!");

Here is the sample run of the above python program illustrating how to delete file:

python 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:

python program delete file

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:

python remove file

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.

Same Program in Other Languages

You may also like to learn or practice the same program in other popular programming languages:

« Previous Program Next Program »


Quick Links
Signup - Login - Give Online Test