- Python Basic Programs
- Python Program Examples
- Python Print Hello World
- Python Get Input from User
- Python Add Two Numbers
- Add Subtract Multiply Divide
- Python Check Even or Odd
- Python Check Prime or Not
- Python Check Alphabet or Not
- Python Check Vowel or Not
- Python Check Leap Year or Not
- Check Reverse equal Original
- Check Positive Negative Zero
- Python Check Armstrong or Not
- Python Check Palindrome or Not
- Python Check Perfect Number
- Python Find Reverse of Number
- Python Count Digits in Number
- Python Add Digits of Number
- Sum of First and Last Digits
- Python Product of Mid Digits
- Sum of Squares of Digits
- Interchange Digits of Number
- Python Sum of n Numbers
- Python Print ASCII Values
- Python Swap Two Numbers
- Python Swap Two Variables
- Python Fahrenheit to Celsius
- Python Celsius to Fahrenheit
- Python Display Calendar
- Python Days into Years, Weeks
- Find Largest of Two Number
- Find Largest of Three Number
- Python Print Fibonacci Series
- Generate Armstrong Numbers
- Python Make Simple Calculator
- Python Add Binary Numbers
- Binary Number Multiplication
- Python Mathematical Programs
- Find Sum of Natural Numbers
- Find Average of n Numbers
- Python Print Multiplication Table
- Print Table using Recursion
- Python Find Average Percentage
- Python Find Grade of Student
- Find Square Root of Number
- Python Print Prime Numbers
- Find Numbers Divisible by
- Python Find Factors of Number
- Python Find Factorial of a Number
- Python Find HCF & LCM
- Python Kilometres to Miles
- Python Find Area of Square
- Python Find Area of Rectangle
- Python Find Area of Triangle
- Python Find Area of Circle
- Python Find Perimeter of Square
- Find Perimeter of Rectangle
- Python Find Perimeter of Triangle
- Find Circumference of Circle
- Python Simple Interest
- Python Solve Quadratic Equation
- Python Different Set of Operations
- Python Display Powers of 2
- Python Find nCr & nPr
- Python Pattern Programs
- Python Print Pattern Programs
- Python Print Diamond Pattern
- Python Print Floyd's Triangle
- Python Print Pascal's Triangle
- Python List Programs
- Python Count Even/Odd in List
- Python Positive/Negative in List
- Python Even Numbers in List
- Python Odd Numbers in List
- Python Sum of Elements in List
- Sum of Odd/Even Numbers
- Python Element at Even Position
- Python Element at Odd Position
- Python Search Element in List
- Python Largest Number in List
- Python Smallest Number in List
- Python Second Largest in List
- Python Second Smallest in List
- Python Insert Element in List
- Python Delete Element from List
- Python Multiply Numbers in List
- Swap Two Elements in List
- Python 1D Array Program
- Python Linear Search
- Python Binary Search
- Python Insertion Sort
- Python Bubble Sort
- Python Selection Sort
- Remove Duplicates from List
- Python Reverse a List
- Python Merge Two List
- Python Copy a List
- Python Conversion Programs
- Python Decimal to Binary
- Python Decimal to Octal
- Python Decimal to Hexadecimal
- Python Binary to Decimal
- Python Binary to Octal
- Python Binary to Hexadecimal
- Python Octal to Decimal
- Python Octal to Binary
- Python Octal to Hexadecimal
- Python Hexadecimal to Decimal
- Python Hexadecimal to Binary
- Python Hexadecimal to Octal
- Python Matrix Programs
- Python Add Two Matrices
- Python Subtract Two Matrices
- Python Transpose Matrix
- Python Multiply Matrices
- Python String Programs
- Python Print String
- Python Find Length of String
- Python Compare Two Strings
- Python Copy String
- Python Concatenate String
- Python Reverse a String
- Python Swap Two Strings
- Python Uppercase to Lowercase
- Python Lowercase to Uppercase
- Python Check Substring in String
- Python Count Character in String
- Count Repeated Characters
- Python Count Word in Sentence
- Python Count Each Vowels
- Python Capitalize Character
- Python Capitalize Word in String
- Python Smallest/Largest Word
- Remove Spaces from String
- Remove Duplicate Character
- Remove Vowels from String
- Remove Punctuation from String
- Python Remove Word in String
- Python Remove Duplicate Words
- WhiteSpace to Hyphens
- Replace Vowels with Character
- Replace Character in String
- Python Sort String in Alphabetical
- Sort Word in Alphabetical Order
- Extract Number from String
- Python Check Anagram Strings
- Python File Programs
- Python Read a File
- Python Write to File
- Python Append Text to File
- Python Copy Files
- Python Merge Two Files
- Python Counts Characters in File
- Python Count Words in File
- Python File Content in Reverse
- Python Lines Contains String
- Python Delete Line from File
- Python Capitalize Word in File
- Python Replace Text in File
- Replace Specific Line in File
- Python Find Size of File
- Python List Files in Directory
- Python Delete Files
- Python Misc Programs
- Python Reverse a Tuple
- Python Merge Two Dictionary
- Python bytes to String
- Python bytearray to String
- Generate Random Numbers
- Python Print Address of Variable
- Python Print Date and Time
- Python Get IP Address
- Python Shutdown/Restart PC
- Python Tutorial
- Python Tutorial
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:
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:
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:
Here is the snapshot of the current directory after executing the program:
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):
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:
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:
Now copy the full path of this folder, like shown in the snapshot given below:
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:
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\fresherearth\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
« Previous Program Next Program »