Skip to content
geeksforgeeks
  • Tutorials
    • Python
    • Java
    • Data Structures & Algorithms
    • ML & Data Science
    • Interview Corner
    • Programming Languages
    • Web Development
    • CS Subjects
    • DevOps And Linux
    • School Learning
    • Practice Coding Problems
  • Courses
    • DSA to Development
    • Get IBM Certification
    • Newly Launched!
      • Master Django Framework
      • Become AWS Certified
    • For Working Professionals
      • Interview 101: DSA & System Design
      • Data Science Training Program
      • JAVA Backend Development (Live)
      • DevOps Engineering (LIVE)
      • Data Structures & Algorithms in Python
    • For Students
      • Placement Preparation Course
      • Data Science (Live)
      • Data Structure & Algorithm-Self Paced (C++/JAVA)
      • Master Competitive Programming (Live)
      • Full Stack Development with React & Node JS (Live)
    • Full Stack Development
    • Data Science Program
    • All Courses
  • Python Tutorial
  • Interview Questions
  • Python Quiz
  • Python Glossary
  • Python Projects
  • Practice Python
  • Data Science With Python
  • Python Web Dev
  • DSA with Python
  • Python OOPs
Open In App
Next Article:
How to Delete files in Python using send2trash module?
Next article icon

How to Delete files in Python using send2trash module?

Last Updated : 16 Jul, 2020
Comments
Improve
Suggest changes
Like Article
Like
Report

In this article, we will see how to safely delete files and folders using the send2trash module in Python. Using send2trash, we can send files to the Trash or Recycle Bin instead of permanently deleting them. The OS module's unlink(), remove() and rmdir() functions can be used to delete files or folders. But, these functions delete the files permanently. The operations cannot be undone if there were any accidental deletions performed. This can be prevented using send2trash.

Modules required

  • OS : The OS module in Python provides functions for interacting with the operating system. OS module comes with Python's Standard Library.
  • send2trash : Send2Trash is a small package that sends files to the Trash (or Recycle Bin) natively and on all platforms. To install it type the below command in the terminal.
pip install send2trash  

Deleting a file or folder

The send2trash() function accepts the location of the file or folder to be deleted.

Python3
import send2trash  send2trash.send2trash("/location/to/file") 

The process of deleting a directory is same as above. If the directory contains files or other folders, those are also deleted. A TrashPermissionError exception is raised, in case a file could not be deleted due to permission error or any other unexpected reason.

Deleting specific files in a directory

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  

Next Article
How to Delete files in Python using send2trash module?

C

cosine1509
Improve
Article Tags :
  • Python
  • python-utility
  • python-modules
  • Python-projects
Practice Tags :
  • python

Similar Reads

    Deleting Files in HDFS using Python Snakebite
    Prerequisite: Hadoop Installation, HDFS Python Snakebite is a very popular Python library we can use to communicate with the HDFS. Using the Python client library provided by the Snakebite package we can easily write python code that works on HDFS. It uses protobuf messages to communicate directly w
    3 min read
    How to Delete Only Empty Folders in Python
    In this article, we are going to see how to delete only empty folders in Python. Before deleting the folder, here is an image showing the files inside the main directory. As the above image is showing that the folder has 2 empty sub-folders and 1 non-empty folder. So, after running the code these 2
    1 min read
    How to delete from a pickle file in Python?
    Python pickle module is used for serializing and de-serializing a Python object structure. Any object in Python can be pickled so that it can be saved on disk. What pickle does is that it “serializes” the object first before writing it to file. Pickling is a way to convert a python object (list, dic
    3 min read
    Delete files older than N days in Python
    In this article, we will learn to delete files that are older than a given number of days using Python. This work can be done manually but it is difficult to do when files are more in number, so we will use Python to make this task simple. We will learn three ways to do this task using Python: Delet
    5 min read
    How to delete a CSV file in Python?
    In this article, we are going to delete a CSV file in Python. CSV (Comma-separated values file) is the most commonly used file format to handle tabular data. The data values are separated by, (comma). The first line gives the names of the columns and after the next line the values of each column. Ap
    2 min read
geeksforgeeks-footer-logo
Corporate & Communications Address:
A-143, 7th Floor, Sovereign Corporate Tower, Sector- 136, Noida, Uttar Pradesh (201305)
Registered Address:
K 061, Tower K, Gulshan Vivante Apartment, Sector 137, Noida, Gautam Buddh Nagar, Uttar Pradesh, 201305
GFG App on Play Store GFG App on App Store
Advertise with us
  • Company
  • About Us
  • Legal
  • Privacy Policy
  • In Media
  • Contact Us
  • Advertise with us
  • GFG Corporate Solution
  • Placement Training Program
  • Languages
  • Python
  • Java
  • C++
  • PHP
  • GoLang
  • SQL
  • R Language
  • Android Tutorial
  • Tutorials Archive
  • DSA
  • Data Structures
  • Algorithms
  • DSA for Beginners
  • Basic DSA Problems
  • DSA Roadmap
  • Top 100 DSA Interview Problems
  • DSA Roadmap by Sandeep Jain
  • All Cheat Sheets
  • Data Science & ML
  • Data Science With Python
  • Data Science For Beginner
  • Machine Learning
  • ML Maths
  • Data Visualisation
  • Pandas
  • NumPy
  • NLP
  • Deep Learning
  • Web Technologies
  • HTML
  • CSS
  • JavaScript
  • TypeScript
  • ReactJS
  • NextJS
  • Bootstrap
  • Web Design
  • Python Tutorial
  • Python Programming Examples
  • Python Projects
  • Python Tkinter
  • Python Web Scraping
  • OpenCV Tutorial
  • Python Interview Question
  • Django
  • Computer Science
  • Operating Systems
  • Computer Network
  • Database Management System
  • Software Engineering
  • Digital Logic Design
  • Engineering Maths
  • Software Development
  • Software Testing
  • DevOps
  • Git
  • Linux
  • AWS
  • Docker
  • Kubernetes
  • Azure
  • GCP
  • DevOps Roadmap
  • System Design
  • High Level Design
  • Low Level Design
  • UML Diagrams
  • Interview Guide
  • Design Patterns
  • OOAD
  • System Design Bootcamp
  • Interview Questions
  • Inteview Preparation
  • Competitive Programming
  • Top DS or Algo for CP
  • Company-Wise Recruitment Process
  • Company-Wise Preparation
  • Aptitude Preparation
  • Puzzles
  • School Subjects
  • Mathematics
  • Physics
  • Chemistry
  • Biology
  • Social Science
  • English Grammar
  • Commerce
  • World GK
  • GeeksforGeeks Videos
  • DSA
  • Python
  • Java
  • C++
  • Web Development
  • Data Science
  • CS Subjects
@GeeksforGeeks, Sanchhaya Education Private Limited, All rights reserved
We use cookies to ensure you have the best browsing experience on our website. By using our site, you acknowledge that you have read and understood our Cookie Policy & Privacy Policy
Lightbox
Improvement
Suggest Changes
Help us improve. Share your suggestions to enhance the article. Contribute your expertise and make a difference in the GeeksforGeeks portal.
geeksforgeeks-suggest-icon
Create Improvement
Enhance the article with your expertise. Contribute to the GeeksforGeeks community and help create better learning resources for all.
geeksforgeeks-improvement-icon
Suggest Changes
min 4 words, max Words Limit:1000

Thank You!

Your suggestions are valuable to us.

What kind of Experience do you want to share?

Interview Experiences
Admission Experiences
Career Journeys
Work Experiences
Campus Experiences
Competitive Exam Experiences