Python Delete a Directory with Files
We must remove unnecessary items from a location. For instance, you might be keeping a notebook with regular inventory information.
Before making a new data file every month, you might want to remove any older ones that are already present.
The program must eventually remove its outdated log files as well.
The following Python methods will be used in this lesson to delete files and folders.
- Using the pathlib and os modules to delete a file.
- Removal from a subfolder
- Delete any folders with a matching sequence. (wildcard)
- Remove unused files.
- Delete a directory's contents (all files and sub-directories)
FunctionDescription
os.remove('file_path') deletes the chosen file.
os.unlink('file_path') deletes the chosen file. in a UNIX system, useful.
pathlib.Path("file_path").unlink() Delete the associated path's associated file or symbolic link.
os.rmdir('empty_dir_path') eliminates the unused subdirectory.
pathlib.Path(empty_dir_path).rmdir() Disconnects and gets rid of the vacant subdirectory.
shutil.rmtree('dir_path')Delete a subfolder and all of the items it holds.
Delete-related features for files and groups
The aforementioned operations completely remove files and directories.
In Python 3.4, the pathlib package was introduced. When your program works on various operating systems, it is suitable.
The numerous standard utility modules that Python provides allow us to construct applications with a variety of features. In this lesson, we'll learn about the modules for deleting files and directories.
One of the most often used Python modules is the os module. This is one of the often used utility modules.
This module provides a number of ways to communicate with a device's operating system. Working with files and folders is made possible.
Shutil is an additional module used for advanced file operations.
In this article, I'll show you how to use these modules to delete files and remove directories in Python. The examples will be tested on my Mac, but you can try them on any other kind of device.
Python File Removal Instructions
The management of files is well supported by Python. There are other ways to delete files, but the os.remove() method is the most common. The methods to remove a file are listed below.
1. Find a file's location
Both a relative and an exact route can be used to remove a file. The file's position on the drive is indicated by the path.
The full directory list needed to find the file is contained in an absolute route. And The file name is followed by the present directory in a relative route.
For instance, an exact route to find samples.txt is /home/Pynative/reports/samples.txt.
2. To eliminate a file, use the os.remove() method.
The OS module for Python provides methods for interacting with the operating system. This module's remove() function can be used to erase or clear a file path.
The os module must first be loaded before you can use the os.remove('file_path') function to remove a file from a disk.
3. To remove a directory, use the shuttle module's rmtree() method.
Import the shutil module and pass the directory path to the shutil.rmtree('path') function to destroy a directory and all of the files it holds.
Example: Python Remove File
The "sales_1.txt" file can be deleted using the following code.
Let's say we wish to delete the sales_1.txt file from E: demos’ files subdirectory.
Currently, these items are located in this directory:
sales_1.txt
sales_2.csv
profits.txt
revenue.txt
Remove the relative path-based file.
import os
# removing a file with a relative path
os.remove("sales_1.txt")
Delete a file using its exact address
os import
os.remove(r"E:demosfilessales_2.txt") # Remove file with exact address
Recognize the syntax for the os.remove() method:
path, *, dir_fd = None; os.remove
To remove a file from a disk, pass the file name to the os.remove('file_path') method.
The requirements that we must meet are listed below.
path - A string-formatted relative or exact path for the file object.
dir_fd - A directory designating the file's position. In the event of an absolute route, this value is disregarded and the default value is none.
An OSError is triggered if the provided file name is a directory.
Before deleting a file, make sure it is there.
If the file is not located in the path, a FileNotFoundError will be generated, so it is best to verify if the file already exists before removing it.
There are two methods to do this:
Use the os.path.exists("file path") method to see if the file is present.
Exception management is used.
os import
r'E:demosfilessales_2.txt' file_path
If file_path os.path.exists, then
os.remove(file_path)
else:
print("The system cannot find the file specified")
Note: Exception handling is recommended over file checking because the file may be changed or destroyed in the meantime. It is the Pythonic method for erasing a file that might or might not be present.
Example 2: Handling exceptions
import os
file_path = r'E:\demos\files\sales_21.txt'
try:
os.remove(file_path)
except:
print("The system cannot find the file specified")
# your code
Utilizing the os.unlink() method to remove a file
If you're using the UNIX operating system, use the unlink() method, which is comparable to remove() but more well-known in the UNIX environment. It is accessible in the OS module.
path, *, dir_fd=None; os.unlink
AD route: A string-formatted relative or exact path for the file object.
dir_fd - A directory designating the file's position. In the event of an absolute route, this value is disregarded and the default value is none.
Let's look at the code to remove the profits.txt file from the present execution route.
File Removal Module for Pathlib
Classes describing filesystem paths with semantics suitable for various operating systems are provided by the pathlib package.
So, we may utilize the pathlib module anytime we need to interact with files in different contexts.
In Python 3.4, the pathlib package was introduced.
The file in the specified path can be deleted using the pathlib.path.unlink() function in the pathlib module.
Additionally, it requires the additional argument missing_ok=False. If the option is set to True, the pathlib module ignores the File Not Found Error.
Otherwise, the FileNotFoundError will be triggered if the path is invalid.
Let's look at the code to remove the "profits.txt" file from the current execution path.
import a module from pathlib
Use the method pathlib.Path() to
import pathlib
# Setting the path for the file
file = pathlib.Path("profits.txt")
# Calling the unlink method on the path
file.unlink()
Get rid of all files in a directory
On occasion, we want to remove every item from a location without erasing the directory itself. To eliminate all items from a directory, follow the procedures listed below.
Utilize the os.listdir(path) method to get a list of the items in a folder. A list of the names of the files and directories in the requested directory is returned.
View each file individually by iterating over the collection using a for loop.
Use the os.remove() function to delete each file.
import os
path = r"E:\demos\files\reports\\"
for file_name in os.listdir(path):
# construct full file path
file = path + file_name
if os.path.isfile(file):
print('Deleting file:', file)
os.remove(file)
Using rmdir, remove an empty directory (folder)
While a directory always contains some files, occasionally there are also vacant folders or groups that are no longer required. The rmdir() function, which is present in both the pathlib and os modules, can be used to remove them.
Employing the os.rmdir() function
The rmdir() method from the os package can be used to remove empty directories.
path, *, dir_fd = None, os.rmdir
The criteria that we must supply to this technique are as follows.
path - A string-formatted relative or exact route for the directory object.
The file location is dir_fd. None is the usual value, and in the event of an absolute route, this value is disregarded.
Note: In the event that the listing
import os
# Deleting an empty folder
directory = r"E:\pynative\old_logs"
os.rmdir(directory)
print("Deleted '%s' directory successfully" % directory)
Output
Deleted 'E:\pynative\old_logs' directory successfully
Implement pathlib.Path.rmdir()
The pathlib module's rmdir() function can also be used to eliminate or delete an empty directory.
Set the directory's name first.
Next, execute that path's rmdir() function.
Let's take a look at an example of how to remove the empty "Images" directory.
import pathlib
# Deleting an empty folder
empty_dir = r"E:\pynative\old_images"
path = pathlib.Path(empty_dir)
path.rmdir()
print("Deleted '%s' directory successfully" % empty_dir)
Shutil can be used to remove a Non-Empty Directory.
We occasionally need to remove a subdirectory and all of the items inside of it. To remove a directory and all of its contents, use the rmtree() function of a shutil module. see Python's remove a non-empty subdirectory.
The shutil module in Python makes it easier to carry out high-level actions on a file or group of files, like transferring or deleting content.
path, ignore_errors=False, and onerror=None in shutil.rmtree
Parameters:
path: The directory to be deleted. The directory's symbolic links are unacceptable.
ignore_errors - If this flag is set to true, errors brought about by unsuccessful deletions will not be taken into account. If true, the function that received the one error property should handle the issue.
import shutil
# Deleting an non-empty folder
dir_path = r"E:\demos\files\reports"
shutil.rmtree(dir_path, ignore_errors=True)
print("Deleted '%s' directory successfully" % dir_path)
Output
Deleted 'E: \demos\files\reports' directory successfully
When removing a non-empty directory, receive the appropriate error message.
Either by catching it in the try-except block or by handling it in a different function whose name we can supply in the oneerror parameter, we may obtain the correct exception message.
import shutil
# Function for Exception Handling
def handler(func, path, exc_info):
print("We got the following exception")
print(exc_info)
# location
dir_path = r'E:\demos\files\reports'
# removing directory
shutil.rmtree(dir_path, ignore_errors=False, onerror=handler)
Final code: To delete File or directory
import os
import shutil
def delete(path):
"""path could either be relative or absolute. """
# check if file or directory exists
if os.path.isfile(path) or os.path.islink(path):
# remove file
os.remove(path)
elif os.path.isdir(path):
# remove directory and all its content
shutil.rmtree(path)
else:
raise ValueError("Path {} is not a file or dir.".format(path))
# file
delete(r'E:\demos\files\reports\profits.txt')
# directory
delete(r'E:\demos\files\reports')
Delete All Files That Match a Pattern
For instance, you could wish to remove files whose names include a particular string.
To locate files and folders whose names match a given pattern, use the Python glob module from the Python Standard Library.
Pathname, *, recursive=False, glob.glob
A list of files or folders that match the pattern supplied in the pathname argument are returned by the glob.glob() function.
Pathname and recursive flag are the two inputs this function requires. ( If set to True it will search files recursively in all subfolders)
The list of wildcard characters used in pattern matching is shown below. We may use these characters to search for patterns.
Asterisk (*): If at least one character matches one or more
A question mark (?) corresponds to one character alone.
Inside the [, we may define a range of alphanumeric characters.
Delete Files with a Specific Extension, for Example
We may need to remove all files with a specific extension.
To find all text files in a folder, use the glob() technique.
To iterate all files, use a for loop.
Eliminate one file every iteration.
To learn how to utilize this to remove files that fit a certain pattern, let's look at a few instances.
Example
import glob
import os
# Search files with .txt extension in current directory
pattern = "*.txt"
files = glob.glob(pattern)
# deleting the files with txt extension
for file in files:
os.remove(file)
Delete file whose name starts with specific string
import glob
import os
# Delete file whose name starts with string 'pro'
pattern = r"E:\demos\files\reports\pro*"
for item in glob.iglob(pattern, recursive=True):
os.remove(item)
Delete any files with the letters in their names
By surrounding them in square brackets, we may provide a range of characters as the search string. ([]).
The example that follows will demonstrate how to remove files with names that contain the letters a through g.
import glob
import os
# search files like abc.txt, abd.txt
pattern = r"E:\demos\files_demos\reports\[a-g]*.txt"
for item in glob.iglob(pattern, recursive=True):
os.remove(item)
Removing all files that fit a pattern across all subfolders
In addition to discovering files inside a folder using the glob() method, the iglob() function, which is identical to the glob() function, may also search for files inside subfolders.
The iglob() method provides iterator options with a list of files inside the folder and any subfolders that fit a pattern.
When looking for files in subdirectories, we must set the recursive value to True. For searching inside the subdirectories, we need to pass ** after the name of the root folder.
import glob
import os
# Searching pattern inside folders and sub folders recursively
# search all jpg files
pattern = r"E:\demos\files\reports\**\*.jpg"
for item in glob.iglob(pattern, recursive=True):
# delete file
print("Deleting:", item)
os.remove(item)
# Uncomment the below code check the remaining files
# print(glob.glob(r"E:\demos\files_demos\reports\**\*.*", recursive=True))
Output
Deleting: E:\demos\files\reports\profits.jpg
Deleting: E:\demos\files\reports\revenue.jpg
Python has a number of modules available for deleting files and directories.
Files can be deleted by:
To remove a single file, use the os.remove() and os.unlink() procedures.
Apply pathlib.If you use Python >= 3.4 and your program runs on several operating systems, you can remove a file by calling Path.unlink().
Removing Directories
Use pathlib or os.rmdir().To remove a directory that is empty, use Path.rmdir()
To recursively destroy a directory and all of its files, use the shutil.rmtree() function.
Because all of the aforementioned functions permanently erase files and directories, use caution when eliminating them.