Python Program to Delete a File

This article deals with some programs created in Python, that deletes a file entered by user at run-time. Here are the list of programs:

Since the program given below deletes a file from the current directory. The current directory means, the folder where the Python source (given below) to delete file is saved. Here is the snapshot of the folder (current directory) before executing the program given below:

delete file in python

As you can see that a file named fresherearth.txt is available in this folder. So I'll delete this file using the program given below. Let's get started.

Delete a File from Current Directory

To delete a file from current directory in Python, you have to ask from user to enter the name of file, then use os.remove() to do the job like show in the program given below:

import os

print("Enter the Name of File: ")
filename = input()

os.remove(filename)
print("\nFile deleted successfully!")

Here is the initial output produced by this Python program:

python delete file

Now supply the input say fresherearth.txt as name of file to delete, press ENTER key to delete it from the current directory. Here is the output produced after providing these inputs:

python program delete file

Here is the snapshot of the current directory after executing the program:

python remove file

As you can see from the above screenshot, the file fresherearth.txt is not present inside the directory, as the file gets deleted using the execution and sample run of above program.

Note - The os module allows us to work with operating system using its predefined functions.

Note - The os.remove() is used to remove or delete a file provided as its argument.

Delete File if Exists

This is the modified version of previous program. This program displays confirmation message to user, whether he/she actually wants delete the file entered by him/her or not. This program also uses try-except to handle the error produced when deleting the file. Let's have a look:

import os

print("Enter File's Name: ", end="")
filename = input()

print("\nDo you really want to delete \"" +(filename)+ "\" ? (y/n) ", end="")
ch = input()
if ch=='y':
    try:
        os.remove(filename)
        print("\nThe File, \"" +(filename)+ "\" deleted successfully!")
    except IOError:
        print("\nThe file \"" +(filename)+ "\" is not available in the directory!")
else:
    print("\nExiting...")

Here is its sample run with input none.txt (a non-existing file):

python delete file if exists

The first statement inside the try block gets executed. That is, os.remove(filename). When this statement produces an error, or something strange happened while deleting the file, then using except, I've processed the IOError (input/output error) to produce or print a message regarding it.

Delete any File from any Folder (Directory)

This program is the complete version of deleting a file from a directory in Python. That is, this program allows user to delete any file from any directory.

import os, glob

print("Enter Full Path of Directory to Operate on: ", end="")
dirpath = input()
os.chdir(dirpath)
print("\nList of Files: ")
chk = 0
for file in glob.glob("*.*"):
    chk = 1
    print(file)

if chk == 0:
    print("Empty Folder!")
else:
    print("\nEnter File's Name to Delete: ", end="")
    filename = input()

    print("\nDo you really want to delete \"" +(filename)+ "\" ? (y/n) ", end="")
    ch = input()
    if ch=='y':
        try:
            os.remove(filename)
            print("\nThe File, \"" +(filename)+ "\" deleted successfully!")
            print("\nDo you want to list remaining files ? (y/n) ", end="")
            ch = input()
            if ch=='y':
                os.chdir(dirpath)
                print("\nList of Files: ")
                for file in glob.glob("*.*"):
                    print(file)
        except IOError:
            print("\nThe file \"" +(filename)+ "\" is not available!")
    else:
        print("\nExiting...")

before executing the program, create another folder say cc like shown in the snapshot given below:

python delete file create another folder

create any two files say one.txt and two.txt inside this newly created folder. Here is the snapshot of the folder that contains two newly created files:

python delete file from any directory

Now copy the full path of this folder, like shown in the snapshot given below:

delete file form any directory python

That is, the full path of newly created folder named cc in my case is C:\Users\DEV\fresherearth\cc. Now execute the above program, and just copy and paste (or type) the full path and press ENTER key, the list of files gets displayed. Then enter the name of file to delete. Here is the snapshot that shows complete sample runs of above program, one by one:

python file delete program

Note - The glob module of Python allows us to match specified pattern as per rules related to Unix shell. Basically this module (in above program) is used to print all files with all extensions using *.*. * before and after dot (.) represents all file's name and all file's extension.

Note - The os.chdir() method is used to change the current working directory. The directory passed as its argument becomes the current directory

The dry run of above program goes like:

Same Program in Other Languages

Python Online Test


« Previous Program Next Program »