Delete a directory or file using Python
Last Updated :
26 Nov, 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:
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 removes or deletes 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.
Example 1: Delete a File in Python
Suppose the file contained in the folder are:
We want to delete file1 from the above folder. Below is the implementation.
Python
# 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:
Example 2: Remove file with absolute path
If the specified path is a directory.
Python
# 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.
Python
# 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.
Example 1: Delete all directories from a Directory
Suppose the directories are -
We want to remove the directory Geeks. Below is the implementation.
Python
# 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:
Example 2: Error Handling while deleting a directory
Handling errors while using os.rmdir() method,
Python
# 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() Method is used to delete an entire directory tree, a path must point to a directory (but not a symbolic link to a directory).
Example 1: Delete a directory and the files contained in it
Suppose the directory and sub-directories are as follow.
# Parent directory:
# Directory inside parent directory:
# File inside the sub-directory:
Example 2: Delete all Files from a Directory
We want to remove the directory Authors. Below is the implementation.
Python
import os
# Directory path
dir_path = r"/content/sample_data"
# List all files in the directory
for filename in os.listdir(dir_path):
file_path = os.path.join(dir_path, filename)
# Check if it is a file (not a subdirectory)
if os.path.isfile(file_path):
os.remove(file_path) # Remove the file
print(f"Deleted file: {filename}")
Output:
Output
Example 3: Ignore error while deleting a directory
By passing ignore_errors = True.
Python
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 4: 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()
Python
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.path module method. First, we have to set the path for the directory, and then we call the rmdir() method on that path
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
Python
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
Similar Reads
How to Change the Owner of a Directory Using Python
We can change who owns a file or directory by using the pwd, grp, and os modules. The uid module is used to change the owner, get the group ID from the group name string, and get the user ID from the user name. In this article, we will see how to change the owner of a directory using Python. Change
5 min read
Python Loop through Folders and Files in Directory
File iteration is a crucial process of working with files in Python. The process of accessing and processing each item in any collection is called File iteration in Python, which involves looping through a folder and perform operation on each file. In this article, we will see how we can iterate ove
4 min read
Delete a Python Dictionary Item If the Key Exists
We are given a dictionary and our task is to delete a specific key-value pair only if the key exists. For example, if we have a dictionary 'd' with values {'x': 10, 'y': 20, 'z': 30} and we want to remove the key 'y', we should first check if 'y' exists before deleting it. After deletion, the update
2 min read
Python Program to Safely Create a Nested Directory
Creating a nested directory in Python involves ensuring that the directory is created safely, without overwriting existing directories or causing errors. To create a nested directory we can use methods like os.makedirs(), os.path.exists(), and Path.mkdir(). In this article, we will study how to safe
2 min read
Python Delete File
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
4 min read
Python Program to Delete Specific Line from File
In this article, we are going to see how to delete the specific lines from a file using PythonThroughout this program, as an example, we will use a text file named months.txt on which various deletion operations would be performed.Method 1: Deleting a line using a specific positionIn this method, th
3 min read
Python Program For Writing A Function To Delete A Linked List
Algorithm For Python:In Python, automatic garbage collection happens, so deleting a linked list is easy. Just need to change head to null. Implementation:Â Python3 # Python3 program to delete all # the nodes of singly linked list # Node class class Node: # Function to initialize the # node object de
2 min read
Python - Delete elements in range
In Python, we often need to remove elements from a list within a specific range. This can be useful when cleaning data or modifying lists based on certain conditions. Using List Comprehension List comprehension is one of the most Pythonic and efficient ways to filter out elements. It is concise, eas
3 min read
Create A File If Not Exists In Python
In Python, creating a file if it does not exist is a common task that can be achieved with simplicity and efficiency. By employing the open() function with the 'x' mode, one can ensure that the file is created only if it does not already exist. This brief guide will explore the concise yet powerful
2 min read
Finding Md5 of Files Recursively in Directory in Python
MD5 stands for Message Digest Algorithm 5, it is a cryptographic hash function that takes input(or message) of any length and produces its 128-bit(16-byte) hash value which is represented as a 32-character hexadecimal number. The MD5 of a file is the MD5 hash value computed from the content of that
3 min read