In this tutorial, you’ll learn how to use Python to delete a file or directory (folder). You’ll learn how to do this using the os
library and the shutil
library to do this. You’ll learn how to do delete a single file, how to delete all files in a directory, and how to delete an entire directory in Python. You’ll also learn how to handle errors, so that if a file or a directory doesn’t exist, that you program will continue to run successfully without crashing.
After reading this guide, you’ll have learned how to use Python to delete files and folders using the os
library, the pathlib
library, and the shutil
library. Why learn three different libraries? Each library comes with specific pros and specific cons – learning how to use these libraries to meet your specific needs can have tremendous benefits on how well your code runs.
You’ll also learn how to make sure your code runs safely, meaning that your code will first check if a file or a directory exist before deleting it. This means that your program won’t crash if it encounters files or folders that don’t exist, allowing your program to continue running.
The Quick Answer: Use os.unlink or shutil.rmtree
Table of Contents
Use Python to Delete a File Using os
Deleting a single file using Python is incredibly easy, using the os.remove()
function. The os
library makes it easy to work with, well, your operating system. Because deleting a file is a common function, the library comes with the .remove()
function built in.
What you need to do is simply pass the path of the file into the function, and Python will delete the filter.
Be careful: there is no confirmation prompt to this, so be sure that this is actually what you want to be doing!
# Delete a single file using os
import os
file_path = "/Users/datagy/Desktop/datagy.py"
# Check if the file exists
if os.path.exists(file_path):
os.remove(file_path)
Let’s explore what we’ve done here:
- We declared our file path, including an extension. If you’re using Windows and don’t want to escape your backslashes, be sure to make the string a raw string by prepending a letter
r
to it. - We run a conditional expression that uses the
os.path.exists()
function to check whether a file exists or not. - If the file exists, we use the
remove()
function to pass in the file we want to delete
In the next section, you’ll learn how to use Python to delete all files in a directory using os
.
Want to learn how to get a file’s extension in Python? This tutorial will teach you how to use the os and pathlib libraries to do just that!
Use Python to Delete all Files in a Directory Using os
In order to delete all the files in a folder with Python, but keep the folder itself, we can loop over each file in that folder and delete it using the method we described above.
In order to do this, we’ll use the helpful glob
module which I’ve described in depth here. What the glob
library helps us do is get the paths to all files in a directory.
Let’s see how we can use the os
and glob
libraries to delete all .csv
files in a given directory. We’ll begin by importing the required libraries:
import os
import glob
glob
is not a preinstalled library. Because of this, you may need to install it. This can be done by using either pip
or conda
in the terminal, such as below:
pip install glob
Let’s see how we can delete all files in a directory using Python:
# Delete all files in a folder using os
import glob
import os
directory = '/Users/nikpi/Desktop/Important Folder/*'
files = glob.glob(directory)
for file in files:
if os.path.exists(file):
os.remove(file)
Let’s take a look at what we’ve done here:
- We use
glob
to generate a list of files in the directory specified. We use the*
wildcard operator to ensure that all files in the directory are gathered. - We then loop over each file in that list, check if it exists, and if it exists, we remove it.
In the next section, you’ll learn how to use the os
library to delete files conditionally, when used with glob
.
Delete Files Conditionally with Python
When working with different files in your operating system, you may want to delete files conditionally. For example, you may want to use Python to delete all files with a certain word in the filename or files that have a certain filetype.
For this, we can use the glob
library to find all files in a folder, especially using a condition. To learn more about the glob
library and how to use it to find all files in a directory using Python, you can check out my in-depth tutorial here.
Now that you’re ready to go, let’s see how we can use the two libraries to find all the files matching a condition and delete them.
# Delete all .csv files in a folder using glob and os
import os
import glob
file_path = '/Users/datagy/Desktop/ImportantDirectory/*.csv'
files = glob.glob(file_path)
for file in files:
os.remove(file)
Let’s explore what we’ve done here:
- We imported the two libraries,
os
andglob
- We then assigned our file path including our condition to the variable
file_path
- This variable was passed into the
glob()
function, which returns a list of all the files matching that condition - We then iterate over the list, deleting every file in the list using the
os.remove()
function
This is a really helpful way to clear up a directory after processing files.
This approach is quite helpful to handle errors. If no files match the condition, then the list is empty and the for loop doesn’t occur.
In the next section, you’ll learn how to use the object-oriented pathlib
library to delete a file using Python.
Want to learn more about Python for-loops? Check out my in-depth tutorial that takes your from beginner to advanced for-loops user! Want to watch a video instead? Check out my YouTube tutorial here.
Use Pathlib to Delete a File using Python
The pathlib
library uses an object-oriented approach to handling files and file paths. Because of this, we can use the library to access attributes of Path objects or apply methods onto the objects. One of these methods is the .unlink()
method, which is used to delete files.
Let’s see how we can use the pathlib library to delete a file:
# Delete a file using Pathlib
import pathlib
path_string = "/Users/nikpi/Desktop/Important Folder/datagy.txt"
path = pathlib.Path(path_string)
path.unlink(missing_ok=True)
You may notice that we passed in an argument into the .unlink()
method. By passing in missing_ok = True
, we tell pathlib to not throw an error if the file doesn’t exist. This is similar to using the os
library to first check if the file exists, but it does save us one line of code.
In the next section, we’ll move on to learning how to use Python to delete entire directories.
Need to automate renaming files? Check out this in-depth guide on using pathlib to rename files. More of a visual learner, the entire tutorial is also available as a video in the post!
Use Python to Delete Directories Using os
Interestingly, both the os
and pathlib
libraries do not have functions or methods that allow you to delete non-empty directories. Because of this, we need to first delete all files in a directory to be able to delete the directory itself.
In order to delete a directory using the os
library, we’ll use the .rmdir()
function. If we try to delete a directory that has files in it, Python will throw an Directory not empty
error.
In order to avoid this, we first need to delete the files in the folder.
Instead of using the glob
library in this example, let’s try using a different function. We’ll loop over the files in the folder using the listdir()
function. Let’s give this a shot:
# Delete a directory using os
import os
path = '/Users/nikpi/Desktop/Important Folder/'
files = os.listdir(path)
for file in files:
file_path = os.path.join(path, file)
os.unlink(file_path)
os.rmdir(path)
Let’s take a look at what we’ve done here:
- We loaded our path variable and used the
os.listdir()
function to generate a list of all the files in the folder - We looped over each file, by first creating a full path to the file using the
os.path.join()
function and the deleting the file - Once all files were deleted, we used the
os.rmdir()
function to delete the directory
Keep in mind, that if the folder contains another folder, then this code will fail. In those cases, read on to see how to use the shutil
library to delete a folder that contains files and other folders.
Want to learn more about Python list comprehensions? Check out this in-depth tutorial that covers off everything you need to know, with hands-on examples. More of a visual learner, check out my YouTube tutorial here.
Use Pathlib to Delete Directories in Python
Similar to the os
library, pathlib
can only delete directories if they are empty. Because of this, in order to delete our folder, we must first delete every file in the folder.
Let’s see how we can do this using the pathlib
library:
# Delete a directory using pathlib
import pathlib
path_string = '/Users/nikpi/Desktop/Important Folder/'
path = pathlib.Path(path_string)
for file in path.iterdir():
file.unlink()
path.rmdir()
We follow a similar path here as we did with the os
library: we looped over each file in the directory and deleted it. Following that, we deleted the directory itself.
In the next section, you’ll learn how to use shutil
to delete directories, even if they have files in them.
Want to learn how to use the Python zip()
function to iterate over two lists? This tutorial teaches you exactly what the zip()
function does and shows you some creative ways to use the function.
Delete Directories Using Shutil in Python
With the two methods above, directories could only be deleted when they didn’t contain any files or folders. Using shutil
, however, we can delete directories using Python even if they are non-empty.
Let’s see how we can use shutil
to delete directories using Python:
# Delete directories in Python using shutil
import shutil
path = '/Users/nikpi/Desktop/Important Folder'
shutil.rmtree(path, ignore_errors=True)
We simply need to pass in the path of a directory into the shutil.rmtree()
function to be able to delete an entire directory, even if it includes files. By using the ignore_errors=True
, we make the execution safer, by preventing the program from crashing if the directory doesn’t exist.
Need to check if a key exists in a Python dictionary? Check out this tutorial, which teaches you five different ways of seeing if a key exists in a Python dictionary, including how to return a default value.
Conclusion
In this post, you learned how to use Python to delete a file or a directory. You learned how to do this using the os
library, the shutil
library, and the pathlib
library. You also learned how to delete all files in a directory using a Python for loop.
To learn more about the pathlib
library, check out the official documentation here.