How to delete files or folders in Python? There are several ways to delete a file or folder, each with its own advantages and use cases. To delete a file or folder, you can use the python os
module, shutil
module, and many others. In this article, we’ll take a look at the different methods for deleting files and folders in Python.
We will also cover some advanced techniques for deleting files in bulk, deleting files based on a pattern or criteria, and removing folders with subfolders.
1. Quick Examples to Delete Files or Folder In Python
The below examples gives a high-level overview of the different methods and scenarios covered in this article. We will discuss each method in much more detail, explaining their advantages and use cases.
# Set the directory path
directory_path = 'Replace Directory Path Here'
# Deleting a File
# Removing a file with os.remove()
import os
os.remove(directory_path + 'myfile.txt')
# Removing a file with pathlib.Path.unlink()
import pathlib
pathlib.Path(directory_path + 'myfile.txt').unlink()
# Deleting Files in Bulk
# Removing all files from a directory
import glob
files = glob.glob(directory_path + '*')
for file in files:
os.remove(file)
# Deleting a Folder
# Removing an empty folder with os.rmdir()
os.rmdir(directory_path + 'empty_directory')
# Removing a non-empty folder with shutil.rmtree()
import shutil
shutil.rmtree(directory_path + 'folder')
2. Deleting File in Python
There are multiple ways to delete a file in Python. These include removing a file with os.remove()
, removing a file with os.unlink()
, and removing a file with pathlib.Path.unlink()
. We will go through each method in detail, explaining how to use them and in what scenarios they are most useful.
2.1 Delete Files using os.remove()
os.remove()
is a built-in function in the Python os
module that can be used to delete a file. It takes a single argument, which is the path to the file you want to delete.
# Import os module
import os
# Delete file
file_path = "file.text"
os.remove(file_path)
os.remove()
will only work if the file exists and the user has the necessary permissions to delete it. If the file doesn’t exist, os.remove()
will raise a FileNotFoundError
. If the user doesn’t have the necessary permissions to delete the file, os.remove()
will raise a PermissionError
.
It is better to use Error Handling when working with os.remove()
for deleting files in python.
# Import os module
import os
file_path = "directory_path/file.txt"
# Exception handling
try:
os.remove(file_path)
print("successfully deleted.")
except FileNotFoundError:
print("File not found.")
except PermissionError:
print("Do not have permission to delete file")
2.2 Delete Files using os.unlink()
It is similar to the os.remove()
function, but os.unlink()
is only available on Unix-based systems, while os.remove()
works on both Unix-based and Windows systems.
If the file is successfully deleted, os.unlink()
does not return a value. If the file cannot be deleted, os.unlink()
raises an exception.
# Import os module
import os
# Delete file using os.unlink()
file_path = "/path/to/file"
os.unlink(file_path)
2.3 Deleting File with pathlib.Path.unlink()
To delete a file using pathlib.Path
, we can use the unlink()
method. The unlink()
method is similar to os.unlink()
, but it provides a more object-oriented interface.
# Import pathlib
from pathlib import Path
# Specify the file path
file_path = Path("file.txt")
# Check if the file exists before deleting it
if file_path.exists():
# Delete the file
file_path.unlink()
print("File deleted successfully.")
else:
print("File not found.")
The main difference between the two methods is that pathlib.Path.unlink()
is part of the pathlib
module, which provides a more object-oriented approach to working with file paths than the os
module.
3. Deleting a Folder in Python
Deleting a folder in Python is similar to deleting a file but requires additional consideration since folders can contain multiple files and subfolders. There are different ways to delete a folder in Python, depending on whether it is empty or contains files and subfolders.
In this section, we will explore how to delete a folder using two different methods: os.rmdir()
for deleting an empty folder and shutil.rmtree()
for deleting a non-empty folder.
3.1 os.rmdir() – Deleting an Empty Folder
The os.rmdir() method can be used to delete an empty folder in Python. It takes the directory path as a parameter and removes it if the directory is empty. If the directory contains files or subdirectories, the method will raise an OSError.
import os
# Delete folder
try:
# Remove empty directory
os.rmdir(directory_path)
print("Directory removed successfully")
except OSError as error:
print(error)
3.2 shutil.rmtree() – Deleting Non-empty Folder
The shutil
module provides the rmtree()
function to remove a directory and its contents, including all subdirectories and files. This function is used to delete non-empty directories.
import shutil
# Delete folder using shutil
try:
shutil.rmtree(folder_path)
print(f"The folder at {folder_path} has been successfully deleted!")
except OSError as e:
print(f"Error: {folder_path} - {e.strerror}.")
4. Removing all Files From a Directory
Sometimes we may need to delete all the files in a directory. There are several ways to achieve this in Python. We can use the os
module to accomplish this task. A simpler way to achieve this is to use the glob
module, which allows us to search for files using patterns.
# Imports
import glob
import os
# Get a list of all the files in the directory
file_list = glob.glob(directory_path + '*')
# Loop through the list of files and delete each file
for file_path in file_list:
try:
os.remove(file_path)
print(f"{file_path} deleted successfully.")
except OSError as e:
print(f"Error: {file_path} : {e.strerror}")
5. Removing Files Matching a Pattern
We can use pattern matching to delete all files or folders in which we are interested and leave the others. Below are some use cases that can help you understand the whole concept.
5.1 Deleting Files with Specific Extension
This involves deleting all files in a directory with a specific extension, such as .txt or .csv.
# This code will delete only text files
extension = ".txt"
for file_name in os.listdir(folder_path):
if file_name.endswith(extension):
os.remove(os.path.join(folder_path, file_name))
5.2 Delete Files – Starts with a Specific String
This involves deleting all files in a directory whose names start with a specific string, such as “image_” or “data_”.
# This code delete all files that start with Python
start_string = "Python"
for file_name in os.listdir(folder_path):
if file_name.startswith(start_string):
os.remove(os.path.join(folder_path, file_name))
5.3 Delete Files – Contains Specific Letters
This involves deleting all files in a directory whose names contain specific letters, such as “log” or “report”.
letters = "abc"
for file_name in os.listdir(folder_path):
if letters in file_name:
os.remove(os.path.join(folder_path, file_name))
6. Summary and Conclusion
We have covered various ways to delete files and folders in Python. This includes how to remove files using os.remove()
, os.unlink()
, and pathlib.Path.unlink()
. And how to remove folders using os.rmdir()
and shutil.rmtree()
. If you have any questions or feedback, feel free to leave a comment below.
Happy coding!
Related Articles
- Why Python creates .pyc files when it is interpreted language?
- How to read a text file into a string and strip newlines?
- File Handling in Python
- How to Print to stderr in Python?
- How do you read from stdin in Python?
- How to Append to a File in Python?
- Extract extension from filename in Python.
- How to read a file line-by-line into a list?
- Import files from different folder in Python.
- How to find current directory and file directory?
- List all Files in a Directory in Python
- How to copy files in Python?
- How to check if file exists?