introduction
In this Byte, we’ll explore how to delete files and folders in Python. This is a common task in many programming and scripting contexts, especially in areas such as data cleaning, deleting temporary files, or when working with file-based databases. Deleting files should be done carefully, as errors can result in data loss, which is often irreversible.
To demonstrate how to do this, we’ll use built-in Python modules such as: os
and shutil
for this task. So, as long as you’re familiar with basic Python syntax and file manipulation, you’ll be fine.
Deleting files in Python
Deleting files in Python is very easy. We’ll discuss two ways to accomplish this task using various Python modules.
Using the “os” module
of os
Python modules have a method called . os.remove()
Can be used to delete files. Here’s a simple example:
import os
# specify the file name
file_name = "test_file.txt"
# delete the file
os.remove(file_name)
In the example above, first os
module. Then specify the name of the file you want to delete.Finally, call os.remove()
To delete a file, use the file name as a parameter.
Note: of os.remove()
Functions can only be deleted File, not a directory. When I try to delete a directory using this function, I get IsADirectoryError
.
Using the “shutil” module
of shutil
The module, which stands for “shell utility,” also provides a way to delete files. shutil.rmtree()
.But why use shutil
when os
Can you work? good, shutil
You can delete an entire directory tree (that is, a directory and all its subdirectories).Let’s see how to delete files shutil
.
import shutil
# specify the file name
file_name = "test_file.txt"
# delete the file
shutil.rmtree(file_name)
the code is quite similar os
For example, right? This is one of the great parts of Python design: consistency between modules.However, please remember shutil.rmtree()
is more powerful and can also delete non-empty directories. This will be discussed in more detail in a later section.
Delete a folder with Python
Moving on to the topic of deleting directories, you can use them again. os
and shutil
A module to perform this task. Both methods are described here.
Using the “os” module
of os
Python modules have a method called . os.rmdir()
This results in empty directory. Here’s how to use it:
import os
# specify the directory you want to delete
folder_path = "/path/to/your/directory"
# delete the directory
os.rmdir(folder_path)
of os.rmdir()
This method only removes empty directories. If the directory is not empty, OSError: [Errno 39] Directory not empty
error.
Using the “shutil” module
If you want to delete a directory that is not empty, use shutil.rmtree()
method from shutil
module.
import shutil
# specify the directory you want to delete
folder_path = "/path/to/your/directory"
# delete the directory
shutil.rmtree(folder_path)
of shutil.rmtree()
Use this method with caution, as it deletes the directory and all of its contents.
hang on! Be sure to double-check the directory path before running the removal code. You don’t want to accidentally delete important files or directories.
Common errors
When handling file and directory operations in Python, it is common to encounter some specific errors. Understanding these errors is important to properly handle them and keep your code running smoothly.
Permission error: [Errno 13] permission denied
One of the common errors that can occur when trying to delete a file or folder is PermissionError: [Errno 13] Permission denied
. This error occurs when you try to delete a file or folder for which your Python script does not have the required permissions.
Here’s an example of what this might look like:
import os
try:
os.remove("/root/test.txt")
except PermissionError:
print("Permission denied")
In this example, we are trying to delete a file in the root directory, which typically requires administrator privileges.When run, this code will be output Permission denied
.
To avoid this error, make sure your script has the necessary permissions to perform its operations. This may require you to run the script as an administrator or change permissions on the file or folder you are trying to delete.
File not found error: [Errno 2] No such file or directory
Another common error is FileNotFoundError: [Errno 2] No such file or directory
. This error is thrown when you try to delete a file or folder that doesn’t exist.
This will look like this:
import os
try:
os.remove("nonexistent_file.txt")
except FileNotFoundError:
print("File not found")
In this example, we are trying to delete a file that does not exist, so Python FileNotFoundError
.
To avoid this, check if the file or folder exists before deleting it, as follows:
import os
if os.path.exists("test.txt"):
os.remove("test.txt")
else:
print("File not found")
OS error: [Errno 39] directory is not empty
of OSError: [Errno 39] Directory not empty
If I try to delete a non-empty directory using , I get an error. os.rmdir()
.
for example:
import os
try:
os.rmdir("my_directory")
except OSError:
print("Directory not empty")
This error can be avoided by making sure the directory is empty before deleting it, or by using the following command: shutil.rmtree()
you can delete the directory and all its contents.
import shutil
shutil.rmtree("my_directory")
Similar solutions and use cases
Python’s file and directory deletion features can be applied to a variety of use cases beyond simply deleting individual files and folders.
Delete files with specific extensions
Imagine you have a directory full of files and you only need to delete files with a specific file extension. .txt
. Python has a versatile library that makes this easy.of os
and glob
Modules are your friend here.
import os
import glob
# Specify the file extension
extension = "*.txt"
# Specify the directory
directory = "/path/to/directory/"
# Combine the directory with the extension
files = os.path.join(directory, extension)
# Loop over the files and delete them
for file in glob.glob(files):
os.remove(file)
This script will remove everything .txt
files in the specified directory.of glob
The module is used to retrieve files/pathnames that match a specified pattern. The pattern here is all files ending with: .txt
.
Delete empty directories
Have you ever noticed that you have a bunch of empty directories that you want to delete? os
module is also useful here.
import os
# Specify the directory
directory = "/path/to/directory/"
# Use listdir() to check if directory is empty
if not os.listdir(directory):
os.rmdir(directory)
of os.listdir(directory)
This function returns a list containing the names of entries in the directory specified by path. If the list is empty, it means the directory is empty and can be safely removed using: os.rmdir(directory)
.
Note: os.rmdir(directory)
Only empty directories can be deleted. If the directory is not empty, OSError: [Errno 39] Directory not empty
error.
conclusion
In this Byte, we looked at how to delete files and folders. We also saw other similar use cases, such as using Python to delete files with specific extensions, empty directories, and nested directories.we harnessed the power os
, glob
and shutil
Modules that perform these tasks.