Python Delete Folder and Contents
The numerous standard utility modules that Python provides allow us to construct applications with a variety of features. We'll learn about the modules for removing files and directories in this tutorial.
The os module is one of the most often used modules available in Python. One of the common utility modules is this one. 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.
I'll be demonstrating how to delete files and remove directories in Python using these modules in this tutorial. The examples below will be tested on a Mac, but you may try them on any other sort of device that has Python installed.
Introduction to the OS Module
The os module enables us to run Linux, Mac, and Windows operating system activities.
This module must first be imported before it can be used:
os import
This module provides several attributes and capabilities that we may use to execute some file-related operations as well as access various OS-related data.
The name field, for instance, returns the name of the operating system module that was imported for the device that you are using the module on. Here is the outcome I receive on my Mac after executing python test.py (where test.py is the file containing my code):
Utilizing the os.remove() function to delete a file or directory
Python's OS module offers tools for communicating with the operating system. When file names or paths are incorrect or unavailable, or when other parameters have the right type but the operating system does not accept them, all methods in the os module throw the OSError exception.
A file path can be removed or deleted in Python using the os.remove() function. A directory cannot be removed or deleted using this approach. The procedure will produce OSError if the supplied path is a directory.
Formatting for os.remove()
os.remove(path, *, dir_fd = None) is the syntax.
Path: A object that resembles a path and represents a file path. A string or an object made up of bytes that represents a path is a path-like object.
A file descriptor relating to a directory is called dir_fd (optional). This parameter's default value is None. dir_fd is not used if the supplied path is absolute.
A '*' in the parameter list denotes that all subsequent arguments (in this example, 'dir_fd') are keyword-only parameters and can only be supplied by name, not as a positional parameter.
Return Type: There is no value returned by this procedure.
There's also the environ object which contains all the environment variables and their values:
import os print(os.environ) { ... 'SHELL': '/bin/zsh', 'HOMEBREW_REPOSITORY': '/opt/homebrew', ... 'ZSH': '/Users/dillion/.oh-my-zsh', 'NVM_DIR': '/Users/dillion/.nvm', 'USER': 'dillion' ... }
My device returns a large number of environment variables once I execute this. You can see the SHELL, ZSH, and USER variables from the list of examples I provided above.
The get() function can be used to retrieve a specific variable's value. Here are a few instances:
import os homeEnv = os.environ.get('HOME') # /Users/dillion shellEnv = os.environ.get('SHELL') # /bin/zsh zshEnv = os.environ.get('ZSH') # /Users/dillion/.oh-my-zsh userEnv = os.environ.get('USER') # dillion
The Shutil Module Overview
The shutil module is for high-level file operations from Python such as copying and deleting files, whereas the os module is more focused on operating system activities (depending on the operating system in use).
Additionally, you need to import this module before using it:
bring shutil
You may use the methods in this module to perform file and directory actions as well. Here are some illustrations.
One option is the move directory, which enables you to transfer a file between two locations. Here is an example of test.py:
import shutil shutil.move("./test.py", "temp/")
The test.py file gets relocated to the temporary directory when I execute Python test.py. You encounter a problem if the directory or file doesn't exist.
The copytree method of this module replicates the contents of a directory to a destination. Let's imagine we have the following files in a folder called directory1/:
file1.py, test, file2.py, directory1, file1.py
This directory has a file with the name file1.py, and the directory test itself contains a file with the name file2.py.
Let's see how to transfer these files from directory1 to directory2, a new directory:
bring shutil
shutil.copytree("directory1/" and "directory2/")
When the aforementioned code is executed, directory2 is formed, and directory1's contents are transferred there.
Following the samples we saw before, let's look at how to delete a file and remove a directory.
Python File Removal Instructions
You may remove (delete) a file using the remove () function of the OS module. Such files are permanently erased rather than placed in the recycle bin. Here's an illustration:
os import os.remove('./temporary.txt') FileNotFoundError: [Errno 2] No such file or directory:
'./temporary.txt' Let me first create the file, which I'll do on my command line as follows: touch temporary.txt echo "new file" > temporary.txt Now I have the temporary.txt file with the "new file" text, which will be removed when I run my Python above: python test.py
# file now deleted Another os import os.path.isfile('./temporary.txt') returns true if fileExists. os.remove('./temporary.txt') if fileExists
By invoking the isfile() function on the path property of the os module, we first determine if temporary.txt is there. Depending on whether that file is present, this function either returns True or False. Before using the delete function, you may use an if statement to examine the returned boolean.
Python Directory Removal Instructions
You may also remove a folder using the rmdir method, which is part of the OS module. The folder must, however, be empty.
Here's an illustration:
os import os.rmdir('directory1/')
If directory1 is already present and empty, it will be removed. You receive a No such file or directory error if it doesn't exist. You receive a Directory not empty error if it exists but is not empty. Therefore, how do non-empty folders get deleted?
Shutil is for high-level file operations, in case you forgot. In this case, it may be used to delete both empty and non-empty folders.
The rmtree method in shutil is used to delete directories and all of their contents, including files, sub-files, subdirectories, etc
deleting a file or directory with the os.rmdir() command
An empty directory can be removed or deleted in Python using the os.rmdir() function. If the supplied path does not lead to an empty directory, OSError will be generated.
Formula for os.rmdir()
os.rmdir(path, *, dir_fd = None) is the syntax.
Parameter:
path: An object that resembles a file path. A string or an object made up of bytes that represents a path is a path-like object.
(Optional) dir_fd a directory referenced by a file descriptor. This parameter's default value is None. dir_fd is not used if the supplied path is absolute.
A '*' in the parameter list denotes that all subsequent arguments (in this example, 'dir_fd') are keyword-only parameters and can only be supplied by name, not as a positional parameter.
Example
bring shutil shutil.rmtree('directory2/')
You receive a No such file or directory error if directory2 does not exist. However, if the directory is present and not empty, it will be removed. It will be erased even if it is empty.
Deleting a file or directory using shutil.rmtree() shutil.A path must point to a directory (but not a symbolic link to a directory) in order to use rmtree() to destroy the complete directory tree.
Shutil.rmtree() syntax Shutil.rmtree (path, False for ignore_errors, None for onerror)
Parameters:
path: An object that resembles a file path. A string or an object made up of bytes that represents a path is a path-like object.
ignore_errors: Errors brought on by unsuccessful deletions will not be taken into account if the value is true.
onerror: Errors are handled by invoking the handler provided by onerror if ignore_errors is false or omitted.
Example 1
# 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 error while deleting a directory:
By passing ignore_errors = True.
Example 2
# 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
Conclusion
You may occasionally wish to create, remove, edit, duplicate, or do other file actions when developing apps. These operations are made feasible by a few common modules that Python has made available.
I've demonstrated in this post how to remove files and directories from a device using the os and shutil standard modules from Python.