Python – Deleting Files and Directories

This is a detailed tutorial on deleting files & folders in python. Learn to delete single or multiple files and directories using the os module.

Deleting a File in Python

The built-in Python module named os provides a simple method remove() to delete a file. Simply import the os module in your python program and use the os.remove() function. You must pass the full name of the file with an extension as the string parameter of this function.

Example. Here we’re deleting a file named hello.txt using this method.

#Importing the os module
import os

#Deleting the file hello.txt
os.remove("hello.txt")

As the program completes its execution without any errors, therefore, the file hello.txt has been deleted successfully.

Python Delete File Example

This way, you can delete any existing file in the specified directory. You must specify the relative or full path. Our file hello.txt was in the same directory as the currently executing python file, so we needed not to specify the full path here.

Also, in case the remove() method does not find the file requested to delete, it will raise FileNotFoundError. Therefore, you must always handle such exception-raising code using Try Except in python.

Checking the Existence of a File

There’s one more way to check if a file exists before running the command to delete it. The os module itself provides another method to check if a file exists or not. The method is os.path.exists("file-path/file.extension") and it takes the file path as the string argument and returns a boolean value i.e. either True or False. It returns True if the file exists and False if it does not.

As it returns a boolean value, you can make use of the If-else statements to use this method along with the os.remove() method to delete a file only after checking if it actually exists or not.

Example. The following python code illustrates the same.

#Importing the os module
import os

#hello1.txt exists, so if block will be executed.
if os.path.exists("hello1.txt"):
    os.remove("hello1.txt")
    print("hello1.txt deleted successfully!")
else:
    print("hello1.txt not found!")
    
#hello2.txt not exists, so else block will be executed.
if os.path.exists("hello2.txt"):
    os.remove("hello2.txt")
    print("hello2.txt deleted successfully!")
else:
    print("hello2.txt not found!")

Observe the output carefully. You can clearly see that as the file hello1.txt exists, it has been deleted successfully while on the other hand hello2.txt does not exist and therefore the print statement written inside the else block is executed.

Python Check If File Exists And Then Delete Example

In the other approach using the Try Except, it will first try to delete the file and if the error will be raised it, will run the code of the except block.

Deleting Multiple Files

To delete multiple files, you either use the same method multiple times or if you want to delete files having names matching with a particular pattern or you simply want to delete all files inside a folder, you can loop through those files using different methods and then can use the os.remove() method inside the loop block.

We’ll use another Python inbuilt module named glob to search for the files and to iterate over them. The glob module provides a method that is also named as glob and takes the pattern string as the argument. Therefore, glob.glob("pattern") will return an iterable that will contain all the file names matching with the particular pattern.

Deleting All Files Inside a Folder

To delete all files inside a particular directory, you simply have to use the * symbol as the pattern string, after specifying the right directory or folder path.

Example. Here we’re deleting all the files inside the folder projects. Here we’re using a python for loop for iteration.

#Importing os and glob modules
import os, glob

#Loop Through the folder projects all files and deleting them one by one
for file in glob.glob("projects/*"):
    os.remove(file)
    print("Deleted " + str(file))

The above code is saved in a directory with the file name delete.py and in this same directory, we have got a folder named projects with three files hello1.txt, hello2.txt, and hello3.txt.

Deleting Multiple Files Python Example

When we run this python file, all the files inside this folder are deleted one by one.

Note. If the folder will contain any sub-folder, then the error may be raised as the glob.glob() method fetches the names of all the folder contents, whether they’re files or sub-folders. Therefore try to make the pattern more specific such as *.* to fetch only the contents that have an extension.

Deleting Files Matching Pattern

The deletion process remains exactly the same as defined in the above section. It’s just that you’ve to modify the pattern string. Therefore, you only need to fetch the right files to further loop through them to do the deletion. Some of the example patterns are given below.

  • *.png will fetch all of the png files.
  • hello*.txt will fetch all the text files starting with the string hello.

Deleting a Folder in Python

To delete a folder in python, we can use another method of the module os, i.e. os.rmdir(). This method also takes the string argument which is the folder name.

Example. Here we’re making use of the os.rmdir() function for deleting a folder.

import os

#Remove the folder/directory named projects
os.rmdir("projects")

The above code will delete the folder or directory named projects. Obviously, all of its contents including the files and sub-folders will also be deleted.

Deleting Multiple Directories

You can use the same method to delete multiple directories that we specified earlier in this article to delete multiple files. You can fetch the iterable for the directories using the glob.glob() pattern matching and then can use the os.rmdir() method inside the loop block to delete the selected directories one by one.

Example. The following python code will delete all the directories that start with the string abc and are contained in the outer directory projects.

#Importing os and glob modules
import os, glob
 
#Loop Through the folder projects all sub-directories and deleting them one by one
for folder in glob.glob("projects/abc*"):
    os.rmdire(file)
    print("Deleted " + str(folder))

This way, you can also delete all the sub-directories of a particular directory by simply using the symbol * as the pattern of the string argument of the glob.glob() method.

Leave a Reply

Your email address will not be published. Required fields are marked *