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:

  • Delete a File from Current Directory
  • Delete File if Exists
  • Delete any File from any Directory. The Name of File and Directory must be entered by user

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 codescracker.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 codescracker.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 codescracker.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\codescracker\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:

  • Using input(), the complete path of folder entered by user gets initialized to dirpath. Therefore dirpath = "C:\Users\DEV\codescracker\cc"
  • The execution of for loop begins, that is the name of first file inside the current directory gets initialized to file and program flow goes inside the loop
  • Inside the loop, using print(), the file's name gets printed. I've initialized 1 to chk to check its value after exiting from the loop, that whether any file is available inside the directory or not
  • Now at second time, the second file gets initialized to file, and the value of it gets printed from inside the loop
  • This process continues until and unless, each and every file gets printed
  • Now after exiting from the loop, the condition chk==0 gets evaluated. That is, if program flow goes inside the loop, means 1 gets initialized to chk and folder has some files. Or when program flow doesn't goes inside the loop, means there is no any file available in the folder. Therefore chk's value remains 0 (as initialized initially)
  • Now program flow goes to else's body (if chk's value is 1, or not equal to 0). All the statements gets executed one by one.
  • Inside its body, the name of file gets received and initialized to filename
  • Again using the input(), I've received another input from user, whether he/she really wants to delete the file or not. That is, if entered character is 'y', then the condition (of if) ch=='y' or 'y'=='y' evaluates to be true, and program flow goes inside its body
  • Now the first statement of try gets executed. That is, os.remove(filename) gets executed. If it raises an IOError (input/output error), then the program flow goes to except's body and print any message written by programmer like file is not available or anything you want to provide
  • But if file is available, then the file gets deleted and using another input(), I've displayed the list of files if user enters 'y'

Same Program in Other Languages

Python Online Test


« Previous Program Next Program »