Delete a directory or file using Python - GeeksforGeeks (2024)

In this article, we will cover how to delete (remove) files and directories in Python. Python provides different methods and functions for removing files and directories. One can remove the file according to their need.

Various methods provided by Python are –

  • Using os.remove()
  • Using os.rmdir()
  • Using shutil.rmtree()
  • Using pathlib.Path(empty_dir_path).rmdir()

Deleting file/dir using the os.remove() method

OS module in Python provides functions for interacting with the operating system. All functions in the os module raise OSError in the case of invalid or inaccessible file names and paths, or other arguments that have the correct type but are not accepted by the operating system.

os.remove() method in Python is used to remove or delete a file path. This method can not remove or delete a directory. If the specified path is a directory then OSError will be raised by the method.

Syntax of os.remove()

Syntax: os.remove(path, *, dir_fd = None)

Parameter: path: A path-like object representing a file path. A path-like object is either a string or bytes object representing a path.

  • dir_fd (optional): A file descriptor referring to a directory. The default value of this parameter is None. If the specified path is absolute then dir_fd is ignored.

Note: The ‘*’ in parameter list indicates that all following parameters (Here in our case ‘dir_fd’) are keyword-only parameters and they can be provided using their name, not as positional parameter.

Return Type: This method does not return any value.

Example 1: Delete a File in Python

Suppose the file contained in the folder are:

Delete a directory or file using Python - GeeksforGeeks (1)

We want to delete file1 from the above folder. Below is the implementation.

Python3

# Python program to explain os.remove() method

# importing os module

import os

# File name

file = 'file1.txt'

# File location

location = "D:/Pycharm projects/GeeksforGeeks/Authors/Nikhil/"

# Path

path = os.path.join(location, file)

# Remove the file

# 'file.txt'

os.remove(path)

Output:

Delete a directory or file using Python - GeeksforGeeks (2)

Example 2: Remove file with absolute path

If the specified path is a directory.

Python3

# Python program to explain os.remove() method

# importing os module

import os

# Directory name

dir = "Nikhil"

# Path

location = "D:/Pycharm projects/GeeksforGeeks/Authors/"

path = os.path.join(location, dir)

# Remove the specified

# file path

os.remove(path)

print("% s has been removed successfully" % dir)

# if the specified path

# is a directory then

# 'IsADirectoryError' error

# will raised

# Similarly if the specified

# file path does not exists or

# is invalid then corresponding

# OSError will be raised

Output:

Traceback (most recent call last): File "osremove.py", line 11, in os.remove(path)IsADirectoryError: [Errno 21] Is a directory: 'D:/Pycharm projects/GeeksforGeeks/Authors/Nikhil'

Example 3: Check if File Exists Before Deleting

Handling error while using os.remove() method.

Python3

# Python program to explain os.remove() method

# importing os module

import os

# path

path = 'D:/Pycharm projects/GeeksforGeeks/Authors/Nikhil'

# Remove the specified

# file path

try:

os.remove(path)

print("% s removed successfully" % path)

except OSError as error:

print(error)

print("File path can not be removed")

Output:

[Errno 21] Is a directory: 'D:/Pycharm projects/GeeksforGeeks/Authors/Nikhil'File path can not be removed

Note: To know more about os.remove() click here.

Deleting file/dir using the os.rmdir() method

os.rmdir() method in Python is used to remove or delete an empty directory. OSError will be raised if the specified path is not an empty directory.

Syntax of os.rmdir()

Syntax: os.rmdir(path, *, dir_fd = None)

Parameter:

  • path: A path-like object representing a file path. A path-like object is either a string or bytes object representing a path.
  • dir_fd (optional): A file descriptor referring to a directory. The default value of this parameter is None. If the specified path is absolute then dir_fd is ignored.

Note: The ‘*’ in parameter list indicates that all following parameters (Here in our case ‘dir_fd’) are keyword-only parameters and they can be provided using their name, not as positional parameter.

Return Type: This method does not return any value.

Example 1: Delete all directories from a Directory

Suppose the directories are –

Delete a directory or file using Python - GeeksforGeeks (3)

We want to remove the directory Geeks. Below is the implementation.

Python3

# importing os module

import os

# Directory name

directory = "Geeks"

# Parent Directory

parent = "D:/Pycharm projects/"

# Path

path = os.path.join(parent, directory)

# Remove the Directory

# "Geeks"

os.rmdir(path)

Output:

Delete a directory or file using Python - GeeksforGeeks (4)

Example 2: Error Handling while deleting a directory

Handling errors while using os.rmdir() method,

Python3

# Python program to explain os.rmdir() method

# importing os module

import os

# Directory name

directory = "GeeksforGeeks"

# Parent Directory

parent = "D:/Pycharm projects/"

# Path

path = os.path.join(parent, directory)

# Remove the Directory

# "GeeksforGeeks"

try:

os.rmdir(path)

print("Directory '% s' has been removed successfully" % directory)

except OSError as error:

print(error)

print("Directory '% s' can not be removed" % directory)

# if the specified path

# is not an empty directory

# then permission error will

# be raised

# similarly if specified path

# is invalid or is not a

# directory then corresponding

# OSError will be raised

Output:

[WinError 145] The directory is not empty: 'D:/Pycharm projects/GeeksforGeeks'Directory 'GeeksforGeeks' can not be removed

Note: To know more about os.rmdir() click here.

Deleting file/dir using the shutil.rmtree()

shutil.rmtree() is used to delete an entire directory tree, a path must point to a directory (but not a symbolic link to a directory).

Syntax of shutil.rmtree()

Syntax: shutil.rmtree(path, ignore_errors=False, onerror=None)

Parameters:

  • path: A path-like object representing a file path. A path-like object is either a string or bytes object representing a path.
  • ignore_errors: If ignore_errors is true, errors resulting from failed removals will be ignored.
  • onerror: If ignore_errors is false or omitted, such errors are handled by calling a handler specified by onerror.

Delete a directory and the files contained in it.

Example 1:

Suppose the directory and sub-directories are as follow.

# Parent directory:

Delete a directory or file using Python - GeeksforGeeks (5)

# Directory inside parent directory:

Delete a directory or file using Python - GeeksforGeeks (6)

# File inside the sub-directory:

Delete a directory or file using Python - GeeksforGeeks (7)

Example: Delete all Files from a Directory

We want to remove the directory Authors. Below is the implementation.

Python3

# Python program to demonstrate

# shutil.rmtree()

import shutil

import os

# location

location = "D:/Pycharm projects/GeeksforGeeks/"

# directory

dir = "Authors"

# path

path = os.path.join(location, dir)

# removing directory

shutil.rmtree(path)

Output:

Delete a directory or file using Python - GeeksforGeeks (8)

Example 2: Ignore error while deleting a directory

By passing ignore_errors = True.

Python3

# Python program to demonstrate

# shutil.rmtree()

import shutil

import os

# location

location = "D:/Pycharm projects/GeeksforGeeks/"

# directory

dir = "Authors"

# path

path = os.path.join(location, dir)

# removing directory

shutil.rmtree(path, ignore_errors=False)

# making ignore_errors = True will not raise

# a FileNotFoundError

Output:

Traceback (most recent call last): File “D:/Pycharm projects/gfg/gfg.py”, line 16, in shutil.rmtree(path, ignore_errors=False) File “C:\Users\Nikhil Aggarwal\AppData\Local\Programs\Python\Python38-32\lib\shutil.py”, line 730, in rmtree return _rmtree_unsafe(path, onerror) File “C:\Users\Nikhil Aggarwal\AppData\Local\Programs\Python\Python38-32\lib\shutil.py”, line 589, in _rmtree_unsafe onerror(os.scandir, path, sys.exc_info()) File “C:\Users\Nikhil Aggarwal\AppData\Local\Programs\Python\Python38-32\lib\shutil.py”, line 586, in _rmtree_unsafe with os.scandir(path) as scandir_it: FileNotFoundError: [WinError 3] The system cannot find the path specified: ‘D:/Pycharm projects/GeeksforGeeks/Authors’

Example 3: Exception handler

In onerror a function should be passed which must contain three parameters.

  • function – function which raised the exception.
  • path – path name passed which raised the exception while removal
  • excinfo – exception info raised by sys.exc_info()

Below is the implementation

Python3

# Python program to demonstrate

# shutil.rmtree()

import shutil

import os

# exception handler

def handler(func, path, exc_info):

print("Inside handler")

print(exc_info)

# location

location = "D:/Pycharm projects/GeeksforGeeks/"

# directory

dir = "Authors"

# path

path = os.path.join(location, dir)

# removing directory

shutil.rmtree(path, onerror=handler)

Output:

Inside handler (, FileNotFoundError(2, ‘The system cannot find the path specified’), ) Inside handler (, FileNotFoundError(2, ‘The system cannot find the file specified’), )

Deleting file/dir using the pathlib.Path(empty_dir_path).rmdir()

An empty directory can also be removed or deleted using the pathlib module’s rmdir() method. First, we have toset the path for the directory, and then wecall the rmdir() method on that path

Syntax of pathlib.Path

Syntax: pathlib.Path(empty_dir_path).rmdir()

Parameter:

  • empty_dir_path: A path-like object representing a empty directory path. A path-like object is either a string or bytes object representing a path.

Return Type: This method does not return any value.

Example: Delete an Empty Directory using rmdir()

In this example, we will delete an empty folder, we just need to specify the folder name if it is in the root Directory

Python3

import pathlib

# Deleting an empty folder

# Put your file address

empty_dir = r"Untitled Folder"

path = pathlib.Path(empty_dir).rmdir()

print("Deleted '%s' successfully" % empty_dir)

Output:

Deleted 'Untitled Folder' successfully


N

nikhilaggarwal3

Improve

Next Article

How to Change the Owner of a Directory Using Python

Please Login to comment...

Delete a directory or file using Python - GeeksforGeeks (2024)

FAQs

Delete a directory or file using Python - GeeksforGeeks? ›

Deleting file/dir using the os.

How do you delete a file directory in Python? ›

to delete a directory:
  1. import shutil.
  2. # Specify the path of the directory to be deleted.
  3. directory_path = '/path/to/directory'
  4. # Check if the directory exists before attempting to delete it.
  5. if os.path. exists(directory_path):
  6. shutil. rmtree(directory_path)
  7. print(f"The directory {directory_path} has been deleted.")
  8. else:
Nov 22, 2023

How do you remove a directory if it exists in Python? ›

rmdir() The Python . rmdir() method allows the user to delete a folder if it exists in the system or computer and does not contain other folders or files. Note: A FileNotFoundError is raised if the directory is not found.

How do I remove a directory structure in Python? ›

Delete an entire directory tree using Python | shutil. rmtree() method
  1. Syntax: shutil.rmtree(path, ignore_errors=False, onerror=None)
  2. Parameters:
  3. path: A path-like object representing a file path. ...
  4. ignore_errors: If ignore_errors is true, errors resulting from failed removals will be ignored.
Jul 5, 2021

How do you delete a folder and subfolders in Python? ›

To delete a folder that has subfolders and files in it, you have to delete all the files first, then call os. rmdir() or path. rmdir() on the now empty folder.

How do I delete a directory file? ›

Deleting or removing directories (rmdir command)
  1. To empty and remove a directory, type the following: rm mydir/* mydir/.* rmdir mydir. ...
  2. To remove the /tmp/jones/demo/mydir directory and all the directories beneath it, type the following: cd /tmp rmdir -p jones/demo/mydir.

What is the fastest way to delete directory Python? ›

We can use functions from Python's built-in os module to delete files and empty folders.
  1. os. remove() will delete a file.
  2. os. rmdir() will delete an empty folder.
Apr 15, 2023

Which method will remove the directory path in Python? ›

os. rmdir() method in Python is used to remove or delete an empty directory. OSError will be raised if the specified path is not an empty directory.

How to use delete in Python? ›

Python del Keyword
  1. ExampleGet your own Python Server. Delete an object: class MyClass: name = "John" del MyClass. print(MyClass) ...
  2. Example. Delete a variable: x = "hello" del x. print(x) Try it Yourself »
  3. Example. Delete the first item in a list: x = ["apple", "banana", "cherry"] del x[0] print(x) Try it Yourself »

How do you check if a directory exists or not Python? ›

How to check if a file or directory exists in Python
  1. try: f = open("filename.txt") except FileNotFoundError: # doesn't exist else: # exists.
  2. import os if os. path. ...
  3. from pathlib import Path my_file = Path("/path/to/file")
  4. if my_file. is_file(): # file exists if my_file.

What is the difference between a file and a folder? ›

A file is the common storage unit in a computer, and all programs and data are "written" into a file and "read" from a file. A folder holds one or more files, and a folder can be empty until it is filled. A folder can also contain other folders, and there can be many levels of folders within folders.

How do you delete a non-empty directory in Python? ›

How to Delete a Non-Empty Directory in Python Using the “shutil” Module. The shutil. rmtree() function is used to delete a non-empty directory and all its contents recursively.

How to check if a file exists in Python? ›

We use the is_file() function, which is part of the Path class from the pathlib module, or exists() function, which is part of the os. path module, in order to check if a file exists or not in Python.

How do I delete a file in Python? ›

One of the most straightforward ways to delete a file in Python is by using the os module's remove() function. This method is concise and well-suited for simple file deletion tasks.

How do I delete all files in a directory using Python? ›

listdir() function can be used in combination with os. remove() to delete all files from a directory. The glob module can be used to delete files that match a specific pattern. Python also allows deletion of files from all subfolders of a directory using the iglob() function from the glob module.

How do you remove a directory and all its subdirectories? ›

If the directory still contains files or subdirectories, the rmdir command does not remove the directory. To remove a directory and all its contents, including any subdirectories and files, use the rm command with the recursive option, -r .

How do you delete a non empty directory in Python? ›

How to Delete a Non-Empty Directory in Python Using the “shutil” Module. The shutil. rmtree() function is used to delete a non-empty directory and all its contents recursively.

How do I remove a directory key in Python? ›

Python | Ways to remove a key from dictionary
  1. Method 1: Remove a Key from a Dictionary using the del.
  2. Method 2: Remove a Key from a Dictionary using pop()
  3. Method 3: Using items() + dict comprehension to Remove a Key from a Dictionary.
Jun 20, 2024

References

Top Articles
Via Rail Train Tickets, Schedules and Fares
Make the Most of Rail Passes on a European Vacation
7 C's of Communication | The Effective Communication Checklist
Jail Inquiry | Polk County Sheriff's Office
No Hard Feelings (2023) Tickets & Showtimes
Tlc Africa Deaths 2021
Citibank Branch Locations In Orlando Florida
Tyson Employee Paperless
Don Wallence Auto Sales Vehicles
Shorthand: The Write Way to Speed Up Communication
Beautiful Scrap Wood Paper Towel Holder
Blairsville Online Yard Sale
Kris Carolla Obituary
Tugboat Information
Bernie Platt, former Cherry Hill mayor and funeral home magnate, has died at 90
Lonadine
Conan Exiles Colored Crystal
Skyward Login Jennings County
Convert 2024.33 Usd
U Break It Near Me
CDL Rostermania 2023-2024 | News, Rumors & Every Confirmed Roster
Puss In Boots: The Last Wish Showtimes Near Cinépolis Vista
BMW K1600GT (2017-on) Review | Speed, Specs & Prices
Riherds Ky Scoreboard
Dulce
Dragonvale Valor Dragon
European Wax Center Toms River Reviews
Drying Cloths At A Hammam Crossword Clue
Sorrento Gourmet Pizza Goshen Photos
Ullu Coupon Code
Mjc Financial Aid Phone Number
4.231 Rounded To The Nearest Hundred
Stickley Furniture
Obsidian Guard's Skullsplitter
Abga Gestation Calculator
Word Trip Level 359
Lowell Car Accident Lawyer Kiley Law Group
Chase Bank Cerca De Mí
How to Get Into UCLA: Admissions Stats + Tips
Giantess Feet Deviantart
Edict Of Force Poe
Hisense Ht5021Kp Manual
Barber Gym Quantico Hours
Simnet Jwu
Cleveland Save 25% - Lighthouse Immersive Studios | Buy Tickets
Gary Vandenheuvel Net Worth
Sleep Outfitters Springhurst
2487872771
Okta Hendrick Login
Billings City Landfill Hours
De Donde Es El Area +63
Secondary Math 2 Module 3 Answers
Latest Posts
Article information

Author: Catherine Tremblay

Last Updated:

Views: 5439

Rating: 4.7 / 5 (67 voted)

Reviews: 90% of readers found this page helpful

Author information

Name: Catherine Tremblay

Birthday: 1999-09-23

Address: Suite 461 73643 Sherril Loaf, Dickinsonland, AZ 47941-2379

Phone: +2678139151039

Job: International Administration Supervisor

Hobby: Dowsing, Snowboarding, Rowing, Beekeeping, Calligraphy, Shooting, Air sports

Introduction: My name is Catherine Tremblay, I am a precious, perfect, tasty, enthusiastic, inexpensive, vast, kind person who loves writing and wants to share my knowledge and understanding with you.