Python Delete Files and Directories

Python Delete Files and Directories

Python Delete Files and Directories : In this article we will see how to delete a python file or folder.

Overview

In python, there are several ways to delete a file or folder. This is often used in programming to avoid doing this action manually. For example, we have a program that creates logs every day and we want to delete them at the end of the day. You can delete all existing log files to make place for the next day’s new file.

There are 5 ways to Python Delete Files and Directories in python :

  • os.remove() Deleting a file
  • os.unlink() Deleting a file
  • pathlib.Path.unlink() Deleting a file
  • os.rmdir() Deleting a directory
  • shutil.rmtree()Deleting a directory containing multiple files recursively

We will therefore review these different methods with an example to illustrate them.

Note : Deleting a file requires write and execute permission on the directory containing the file. Otherwise, you will get an ErrorPermission.

Delete a File with Python os.remove()

When working with files in python, it is often necessary to remove a particular file and this is where the os.remove() function comes in handy. It allows you to simply delete a file and its syntax and is easy to understand:

import os

os.remove(file)
 

The first thing to do is to import the OS module that contains the remove() function. The OS module is a library often used in python to interact with the operating system.

The remove() function takes a single parameter that corresponds to the location of the file. The path can be absolute or relative :

import os

os.remove("/home/amiradata/python/data.csv") # Absolute Path
os.remove("data.csv") # Relative Path
 

Note : The os.remove() function only works if you want to delete a file. If you want to delete a folder with this function, it will return an error in your code.

Python delete file if exists

When we want to delete a file, it is important to check if this file really exists on the computer in order to avoid that the program returns an error saying that the file does not exist. Here is an example of an error returned when python can’t find the file specified in the remove() function:

import os

os.remove("data.csv")
 

Output:

Traceback (most recent call last):
File "test.py", line 3, in
os.remove("data.csv")
FileNotFoundError: [WinError 2] Le fichier spécifié est introuvable: 'data.csv'

To verify that the file exists, our beloved OS module has a function to check the existence of a file called os.path.exists(). Here is the code to do this verification.

import os
filePath = 'data.csv';

if os.path.exists(filePath):
    os.remove(filePath)
else:
    print("Can't delete the file : Doesn't exist !")
 

Output:

Can't delete the file : Doesn't exist !

Delete a File using os.unlink()

the os.unlink() function works on the same principle as os.remove(). Here is the syntax of the function:

import os

os.unlink(file)
 
import os

os.unlink("data.csv")

This function only works with files. If you specify a folder, you will get an IsADirectoryError error.

Delete a File using pathlib.Path.unlink()

The pathlib module is available since Python 3.4. Before this version, you will have to install it yourself with the help of pip. This module provides an object-oriented interface that allows you to work with file system paths on different operating systems.

To delete a file using this function, you will need to run the following code :

from pathlib import Path

file = Path('/home/amiradata/python/data.csv')

try:
    file.unlink()
except OSError as e:
    print("Error: %s : %s" % (file, e.strerror))
 
    

The try-catch makes it possible to check if the file exists well before deleting it. If the file does not exist, it raises an OSError exception.

Python Delete Empty Directory using os.rmdir()

We saw earlier that it was impossible to delete a folder with the os.remove(), os.unlink() and pathlib.Path.unlink() functions. The OS module therefore offers the os.rmdir() method which allows to delete an empty folder only.

Here is the syntax of the function os.rmdir()

import os

os.rmdir(folder)
 

The os.rmdir() method accepts a parameter that corresponds to the path of the folder you want to delete.

And here is an example of the function :

import os

os.rmdir(/home/amiradata/java)
 

Note: os.rmdir() returns a Permission denied if the folder is not empty

Python Delete Directory With Files using shutil.rmtree()

we have seen that the os.rmdir() method only allows to delete empty directories. The shutil.rmtree() method allows to solve this kind of problem. It allows to delete all the contents of a folder (whether files or sub-folders). Here is the syntax :

import shutil

shutil.rmtree(file)
import shutil

shutil.rmtree(/home/amiradata/python)
 

This function did remove the python folder but also the data.csv file.

Note: This function is very dangerous because it deletes everything without any system check. So you can easily lose your data by using this function. I advise you to use it sparingly.

Delete Multiple Files using Pattern matching

If you want to delete several .txt files from a folder for example you can use the glob module in the following way:

import os
import glob

files = glob.glob('/home/amiradata/python/**/*.txt', recursive=True)

for f in files:
    try:
        os.remove(f)
    except OSError as e:
        print("Error: %s : %s" % (f, e.strerror))
  

This code will search all the txt files in the subfolders of the python folder and will delete recursively using the recursive=True parameter.

Conclusion

We have seen that the Python language provides several modules to manage the deletion of files or folders. I advise you to be very careful in the use of these functions, it can be difficult to get them back afterwards (they are not moved in the recycle bin 🙂 ).

If you need help using these functions, please don’t hesitate to leave me a comment!

If you want to learn more about python, you can read this book (As an Amazon Partner, I make a profit on qualifying purchases) :

Back to the Python Menu

Published
Categorized as Python

By ayed_amira

I'm a data scientist. Passionate about new technologies and programming I created this website mainly for people who want to learn more about data science and programming :)

Leave a comment

Your email address will not be published.