Python Delete File - GeeksforGeeks (2024)

Last Updated : 14 Dec, 2023

Summarize

Comments

Improve

When any large program is created, usually there are small files that we need to create to store some data that is needed for the large programs. when our program is completed, so we need to delete them. In this article, we will see how to delete a file in Python.

Methods to Delete a File in Python

  1. Python Delete File using os. remove
  2. Delete file in Python using the send2trash module
  3. Python Delete File using os.rmdir

Check if the file exists or not

Command to install OS Module:

pip3 install os

For Delete a File in Python, you can use the os.path.exists() function to check if a file exists. Here’s a simple example: Replace 'path/to/your/file.txt' with the actual path of the file you want to check. The os.path.exists() function returns True if the file exists and False otherwise. The code then prints a message based on the existence of the file.

Python3

import os

def check_file_existence(file_path):

if os.path.exists(file_path):

print(f'The file "{file_path}" exists.')

else:

print(f'The file "{file_path}" does not exist.')

# Example usage:

file_path = 'path/to/your/file.txt'

check_file_existence(file_path)

Output :

The file "path/to/your/file.txt" does not exist.

Delete a File in Python 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: Delete the file from your current directory

This is the simple code to delete the file from your current directory.

Example 2: Detailed Explanation

In below code Python script prompts the user to input a filename for deletion. If the input is ‘quit’, the program exits; otherwise, it attempts to remove the specified file using `os.remove()`. A success message is then printed.

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 Delete File - GeeksforGeeks (1)

A sample run of the program

Python Delete File - GeeksforGeeks (2)

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

Python Delete File - GeeksforGeeks (3)

The deletion:

Python Delete File - GeeksforGeeks (4)

The Working Output:

Python Delete File - GeeksforGeeks (5)

Delete a 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.

Example : In this script walks through files in the directory ‘/Users/tithighosh/Documents’ using `os.walk`. For each ‘.txt’ file found, it prints its path and uses `send2trash` to move it to the system trash, avoiding permanent deletion. The script effectively trashes all ‘.txt’ files in the specified directory and its subdirectories.

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.txtdeleted : /Users/tithighosh/Documents/e_also_big_output.txtdeleted : /Users/tithighosh/Documents/res.txtdeleted : /Users/tithighosh/Documents/tk.txt

Python a Delete File using os.rmdir

In the os.rmdir method removes an empty directory specified by the given path. It is important to note that if the directory contains any files or subdirectories, the method will raise an OSError. Therefore, it’s essential to ensure that the directory is empty before using this method.

Example : In this example, replace 'path/to/empty_directory' with the actual path of the empty directory you want to delete. The delete_empty_directory function attempts to remove the specified directory using os.rmdir and prints a success message if the deletion is successful

Python3

import os

def delete_empty_directory(directory_path):

try:

os.rmdir(directory_path)

print(f'The directory "{directory_path}" has been successfully deleted.')

except OSError as e:

print(f'Error: {e}')

# Example usage:

directory_to_delete = 'path/to/empty_directory'

delete_empty_directory(directory_to_delete)

Output :

The directory "path/to/empty_directory" has been successfully deleted.

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...

Python Delete File - GeeksforGeeks (2024)
Top Articles
Why Real Estate Development Companies Need Digital Marketing
How to Get a Small Business Loan and Navigate the Tax Implications
Friskies Tender And Crunchy Recall
Aberration Surface Entrances
Tesla Supercharger La Crosse Photos
15 Types of Pancake Recipes from Across the Globe | EUROSPAR NI
According To The Wall Street Journal Weegy
Craigslist Cars And Trucks Buffalo Ny
Baseball-Reference Com
The Murdoch succession drama kicks off this week. Here's everything you need to know
Accuradio Unblocked
Gmail Psu
Gino Jennings Live Stream Today
Busby, FM - Demu 1-3 - The Demu Trilogy - PDF Free Download
Slope Tyrones Unblocked Games
Costco Gas Foster City
1v1.LOL - Play Free Online | Spatial
Rugged Gentleman Barber Shop Martinsburg Wv
Shopmonsterus Reviews
Craigslist Pearl Ms
Brazos Valley Busted Newspaper
Pirates Of The Caribbean 1 123Movies
Craigslist Apartments Baltimore
Craiglist.nj
Dei Ebill
Busted Mugshots Paducah Ky
Ullu Coupon Code
Pokémon Unbound Starters
San Jac Email Log In
Astro Seek Asteroid Chart
Babydepot Registry
Missing 2023 Showtimes Near Mjr Southgate
Utexas Baseball Schedule 2023
Workboy Kennel
The Ride | Rotten Tomatoes
Tas Restaurant Fall River Ma
Kips Sunshine Kwik Lube
Unlock The Secrets Of "Skip The Game" Greensboro North Carolina
AsROck Q1900B ITX und Ramverträglichkeit
Keeper Of The Lost Cities Series - Shannon Messenger
Spectrum Outage in Genoa City, Wisconsin
Husker Football
manhattan cars & trucks - by owner - craigslist
UT Announces Physician Assistant Medicine Program
Conan Exiles Tiger Cub Best Food
Gw2 Support Specter
This Doctor Was Vilified After Contracting Ebola. Now He Sees History Repeating Itself With Coronavirus
Ratchet And Clank Tools Of Destruction Rpcs3 Freeze
Congruent Triangles Coloring Activity Dinosaur Answer Key
De Donde Es El Area +63
Emmi-Sellers
Latest Posts
Article information

Author: Merrill Bechtelar CPA

Last Updated:

Views: 6082

Rating: 5 / 5 (50 voted)

Reviews: 81% of readers found this page helpful

Author information

Name: Merrill Bechtelar CPA

Birthday: 1996-05-19

Address: Apt. 114 873 White Lodge, Libbyfurt, CA 93006

Phone: +5983010455207

Job: Legacy Representative

Hobby: Blacksmithing, Urban exploration, Sudoku, Slacklining, Creative writing, Community, Letterboxing

Introduction: My name is Merrill Bechtelar CPA, I am a clean, agreeable, glorious, magnificent, witty, enchanting, comfortable person who loves writing and wants to share my knowledge and understanding with you.