How to delete the contents of a folder in Python?

File handling in Python programming is a skill every python developer must have. In this python article, we will learn to delete the contents of a folder in Python programming language.

Table Of Contents

Method 1 : Using OS module

We can use OS module to delete the contents of a folder in Python. The OS module comes pre-installed with python programming language and it is the one of the most used module for interaction with Operating System and file systems.

os.remove()

This method is used to delete a file from a folder, But this method can only delete files, it cannot delete any folder. This function raises an error, if the file provided is not found or if you do not have permission to delete the file.

See the Example code below:

CODE :

# importing os module
import os

# os.system() executes system commands.
# this will create a file named file1.txt in the working directory.
os.system('echo Hello, world! > file1.txt')

# this will create a file named file2.txt in the working directory.
os.system('echo Hello, world! > file2.txt')

# this will create a folder/directory named os in the working directory.
os.system('mkdir os')

# this will print the directories/files in the working directory.
os.system('dir')

# this will remove the file1.txt from the working folder.
os.remove('./file1.txt')

# this will print the directories/files in the working directory.
os.system('dir')

OUTPUT :

 613 code.py
 16 file1.txt
 16 file2.txt
 os
 3 File(s) 645 bytes
 3 Dir(s) 187,809,103,872 bytes free

 .
 ..
 740 code.py
 16 file2.txt
 os
 2 File(s) 756 bytes
 3 Dir(s) 187,807,252,480 bytes free

In the above example code and output, you can see os.remove() can be used to delete a file of folder. You can see file1.txt has been removed using the remove() method. In remove() method you can pass the path of the file to delete it.

The unlink() function of os module is used to delete contents of a folder in Python programming language. This function takes an argument which is path of the file which needs to be deleted. See the example code below.

CODE :

# importing os module
import os

#this will print the directories/files in the working directory.
os.system('dir')

# listdir() returns the name of the files/folders in a list.
dir = os.listdir('./os')
print(dir)

# using unlink() function to delete file3.txt
os.unlink('./os/file3.txt')

# listdir() returns the name of the files/folders in a list.
dir = os.listdir('./os')
print(dir)

OUTPUT :

 1,405 code.py
 16 file2.txt
 os
 2 File(s) 1,421 bytes
 3 Dir(s) 187,454,382,080 bytes free

 ['file3.txt', 'file4.txt', 'New folder']

 ['file4.txt', 'New folder']

In the above example code and output you can see unlink() function has been used to delete content(file3.txt) from the os file in the working directory. Here we have used os.listdir() which takes path as an argument and returns the contents in the given directory in a list.

Method 2 : Using shutil module

Shutil module can also be used to delete the contents of a folder in Python programming language. The Shutil module comes pre-installed with python programming language and used to perform high level file operations. Here we will be using rmtree() function of Shutil module to delete the contents of a folder in Python.

shutil.rmtree() : This function is used to remove the specified directory and all of its contents. This function takes one argument which is the path of the directory which needs to be deleted.

This function also raises an error OSError if the file specified is not found or the rmtree() function fails to delete the given file or directory.

See the example code below:

CODE :

#importing shutil module.
import shutil

# importing os.
import os 

# listdir() returns the directories/files of the path given in a list.
dir = os.listdir('./')
print(dir)

# path assigned to os folder of the working directory.
path = './os'

# deleting the os folder and all its contents.
shutil.rmtree(path)

# listdir() returns the directories/files of the path given in a list.
dir = os.listdir('./')
print(dir)

OUTPUT :

['code.py', 'file2.txt', 'os']
['code.py', 'file2.txt']

In the code and output above you can see, shutil.rmtree() has been used to delete os folder and all its contents.

Method 3: Using pathlib module

Another module which can be used to delete the contents of a folder in Python is pathlib module which comes pre-installed with python programming language. It provides an object-oriented interface for working with file and directory paths, which makes it easier to write code that is more readable and less prone to errors.

pathlib.unlink() : pathlib.unlink() is similar to the os.unlink() and this function is used to remove file from the file system. This method raises an error FileNotFoundError if the path of the file passed is not found. Also this function raises an error IsADirectoryError if the path refers to a directory/folder.

This function is often used with Path() function or referred as pathlib.Path.unlink().

pathlib.Path() : This is a class that represents a file system path. This function provides a convenient way to work with file paths in a cross-platform manner. This function takes an argument as a string which is the Path of the file.

Now see an Example code and output of the pathlib.Path.unlink() method.

CODE :

# importing pathlib
import pathlib

import os

# this will print the directories/files in the working directory.
os.system('dir')

# listdir() returns the directories/files of the path given in a list.
dir = os.listdir('./pathlib')
print(dir)

# using unlink() function to delete file3.txt inside the pathlib folder.
pathlib.Path('./pathlib/file3.txt').unlink()

# listdir() returns the directories/files of the path given in a list.
dir = os.listdir('./pathlib')
print(dir)

OUTPUT :

['file3.txt', 'file4.txt']

 2,361 code.py
 16 file2.txt
 pathlib

 2 File(s) 2,377 bytes
 3 Dir(s) 186,331,185,152 bytes free

['file4.txt']

In the example code and output above you can see, In the working directory we have a folder named pathlib in which we have two text files. By using pathlib.Path.unlink(), the file file3.txt has been deleted.

Summary

In this Python article, on How to delete the contents of a folder in Python? We learned to delete the contents of the folder using three different modules. In OS Module, we have os.remove() and os.unlink() functions both these functions delete the files of the given path. Next we have shutil module, In which we have shutil.rmtree() function. This function deletes the entire directory and its contents, also raises an error of OSError when the file specified is not found or the rmtree() function fails to delete the given file or directory. Also we have pathlib() module, In which we have unlink() function along with Path() class of pathlib module. This function also deletes the contents of the given directory. This also raises and error FileNotFoundError if the path of the file passed is not found. Also this function raises an error IsADirectoryError if the path refers to a directory/folder. This method can only be used to delete the files not the folders.

So, all the methods can be used according to the requirement but the pathlib module provides an edge over the other modules because this method does not delete the entire folder. If path of a directory is passed then this will raise an error of IsADirectoryError.

Make sure to read and write example codes in order to have a better understanding of this problem. Thanks.

Leave a Comment

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

This site uses Akismet to reduce spam. Learn how your comment data is processed.

Scroll to Top