Python Program to delete a file
Ever wanted to delete a file, that too from a Python program, with a few lines of code? Well, you are in the right place. Today we are going to learn How to Delete Files in Python.
Required Modules
Since Python OS is an inbuilt library but If you don’t have the OS library, then open Command Prompt and write the following command:
pip install os
Python Delete File using os.remove
We will be importing the OS library and going to use the os.remove() function to remove the desired file.
Example 1:
This is the simple code to delete the file from your current directory.
Python3
import osos.remove("starwars.txt") |
Example 2:
A detailed explanation of the above example, to check if the file exists before you try to delete it.
Python3
import osprint("Enter 'quit' for exiting the program")filename = input('Enter the name of the file, \ that is to be deleted : ')if filename == 'quit': exit()else: print('\nStarting the removal of the file !') os.remove(filename) print('\nFile, ', filename, 'The file deletion \ is successfully completed !!') |
Output:
The desired file to be deleted:

A sample run of the program

When we enter the name of the file to be deleted:

The deletion:

The Working Output:

Delete files in Python using send2trash module
We can use the os.walk() function to walk through a directory and delete specific files. In the example below, we will delete all ‘.txt’ files in the given directory.
Python3
import osimport send2trash# walking through the directoryfor folder, subfolders, files in os.walk('/Users/tithighosh/Documents'): for file in files: # checking if file is of .txt type if file.endswith('.txt'): path = os.path.join(folder, file) # printing the path of the file # to be deleted print('deleted : ', path ) # deleting the file send2trash.send2trash(path) |
Output:
deleted : /Users/tithighosh/Documents/cfile.txt deleted : /Users/tithighosh/Documents/e_also_big_output.txt deleted : /Users/tithighosh/Documents/res.txt deleted : /Users/tithighosh/Documents/tk.txt
Related Article
Delete a directory or file using Python
How to delete data from file in Python
Delete files older than N days in Python


Please Login to comment...