There are various modules that can be easily used to delete a file or folder in Python. In this article, we are going to look at the various methods used to delete a file or folder in Python.
Method 1: The os module
A Quick Recap to the OS Module:
The OS module is a module in Python that has various pre-defined functions which can be used to work upon the directories. You can use the OS module for performing the following operations on directories:
1. To create and remove a directory.
2. Listing the files of a directory.
3. Changing the current directory.
The first module that helps us to delete files and folders using Python scripts is the
os module. It arguably provides the easiest way to delete a file or folder in Python. The
os module permits developers to interface with the operating system and other frameworks using Python.
Note: It is important to import the
os module before using it in your program. Use the following command to import the
os module in your program:
We will now explore numerous methods of the
os module that allow us to delete files and folders.
os.remove() method deletes a file from the operating system. The method must be used when you want to delete a single file. However, we cannot delete a folder/directory using the
os.remove() method. To delete a directory, you can use the
os.rmdir() method, which will be discussed in a while.
Example: This following code will remove the file ‘
file.txt‘ from the current folder assuming the Python script resides in the same directory:
# Importing the os module import os # Checking if the given file exists if os.path.exists('file.txt'): # If yes, delete it using the os.remove() method os.remove('file.txt') print("File has been deleted!") else: print("File not found in the directory")
Caution: If the path you want to delete is a directory, the
os.remove() method will raise an
Are you working in Python 2? In that case you can use the
os.unlink() method to delete a file or folder. The methods
os.unlink() are semantically identical.
# Importing the os module import os # Checking if the given file exists if os.path.exists('file.txt'): os.unlink('file.txt') print('File deleted successfully!') else: print("File not found in the directory")
File deleted successfully!
os.rmdir() method in Python is used to delete the directory path. However, the drawback of this method is that it only works if the directory is empty. It raises
OSError if the directory is not empty.
os.rmdir(path, *, dir = None)
Example: In the following example, we will be deleting the folder named ‘
# Importing the os module import os # Listing all the directories using os.listdir print("All the directories-") print(os.listdir('.')) # Deleting the path os.rmdir("folder") # listing all the directories after deleting the directory path print("All the directories after deleting the path-") print(os.listdir('.'))
All the directories- ['filedeletion.py', 'folder', 'test'] All the directories after deleting the path- ['filedeletion.py', 'test']
Discussion: Before deleting the folder, when we listed all the folders within the current directory, we found that there were three folders/directories. After executing the
os.rmdir() method the folder named ‘
folder‘ was deleted and we have two folders remaining.
Caution: If the directory was not empty, the Python would raise
OSError as shown below:
All the directories- ['filedeletion.py', 'folder', 'test'] Traceback (most recent call last): File "E:\Python Tutorials\filedeletion.py", line 10, in <module> os.rmdir("folder") OSError: [WinError 145] The directory is not empty: 'folder'
We can handle this error by using try and except blocks in Python.
import os print("All the directories-") print(os.listdir('.')) try: os.rmdir("folder") except: print("Folder is not Empty and Cannot be deleted!") print("All the directories after deleting the path-") print(os.listdir('.'))
All the directories- ['filedeletion.py', 'folder', 'test'] Folder is not Empty and Cannot be deleted! All the directories after deleting the path- ['filedeletion.py', 'folder', 'test']
Method 2: The glob Module
The second module that we can use is the
glob module in Python that enables us to delete files by using wildcards. To remove files by matching a wildcard pattern such as
'*.dat', first obtain a list of all file paths that match it using
glob.glob(pattern). Then iterate over each of the filenames in the list and remove the file individually using
os.remove(filename) in a for loop.
Example: The following example will showcase how the
glob module will delete all the files in the current directory with the .jpg extension.
import glob import os # Get all files with suffix jpg files = glob.glob('*.jpg') # Iterate over the list of files and remove individually for file in files: print("Deleting image: ",file) os.remove(file)
⦿ Python Delete Files in Folder and Subfolders with Extension
You can also delete the files in the directory and the subdirectories under it recursively by using the “**` pattern and setting the
recursive argument to
True within the
import glob import os files = glob.glob('folder/**/*.txt', recursive = True) for file in files: try: os.remove(file) print("The files have been deleted successfully!") except OSError as error: print(error) print("The files cannot be deleted")
Method 3: The shutil Module
Another module that helps us to work with files and folders in Python is the
shutil.rmtree() method is used in Python to delete the directories that aren’t empty. It enables us to delete all the files in a directory recursively.
shutil.rmtree(path, ignore_errors=False, onerror=None)
# Importing the shutil module import shutil # Specifying the directory path path = "D/Project" # Deleting the path using try and block try: shutil.rmtree (path) print("The given directory is deleted successfully!") except OSError as error: print(error) print("The given directory cannot be deleted!")
The given directory is deleted successfully!
In this tutorial, we looked at various modules in Python like os, glob, and shutil that facilitate us with different methods to delete a file in Python. Depending on the requirement, you have to use the modules and the functions accordingly within your script. I hope this article managed to answer all your queries about file deletion from within a Python script. For more tutorials and discussions, please subscribe and stay tuned.
Recommended Read: How Do I List All Files of a Directory in Python?
Python One-Liners Book: Master the Single Line First!
Python programmers will improve their computer science skills with these useful one-liners.
Python One-Liners will teach you how to read and write “one-liners”: concise statements of useful functionality packed into a single line of code. You’ll learn how to systematically unpack and understand any line of Python code, and write eloquent, powerfully compressed Python like an expert.
The book’s five chapters cover (1) tips and tricks, (2) regular expressions, (3) machine learning, (4) core data science topics, and (5) useful algorithms.
Detailed explanations of one-liners introduce key computer science concepts and boost your coding and analytical skills. You’ll learn about advanced Python features such as list comprehension, slicing, lambda functions, regular expressions, map and reduce functions, and slice assignments.
You’ll also learn how to:
- Leverage data structures to solve real-world problems, like using Boolean indexing to find cities with above-average pollution
- Use NumPy basics such as array, shape, axis, type, broadcasting, advanced indexing, slicing, sorting, searching, aggregating, and statistics
- Calculate basic statistics of multidimensional data arrays and the K-Means algorithms for unsupervised learning
- Create more advanced regular expressions using grouping and named groups, negative lookaheads, escaped characters, whitespaces, character sets (and negative characters sets), and greedy/nongreedy operators
- Understand a wide range of computer science topics, including anagrams, palindromes, supersets, permutations, factorials, prime numbers, Fibonacci numbers, obfuscation, searching, and algorithmic sorting
By the end of the book, you’ll know how to write Python at its most refined, and create concise, beautiful pieces of “Python art” in merely a single line.