The Wayback Machine - https://web.archive.org/web/20230628042926/https://www.geeksforgeeks.org/python-program-to-delete-a-file/
Skip to content
Related Articles
Open In App

Related Articles

Python Program to delete a file

Improve Article
Save Article
Like Article
Improve Article
Save Article
Like Article

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 os
os.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 os
print("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: 

Python Program to delete a file

 

A sample run of the program 

Python Program to delete a file

 

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

Python Program to delete a file

 

The deletion: 

Python Program to delete a file

 

The Working Output: 

Python Program to delete a file

 

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 os
import send2trash
 
# walking through the directory
for 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


Last Updated : 06 Apr, 2023
Like Article
Save Article
Similar Reads
Related Tutorials