How to Safely Delete Files and Folders using the send2trash module in Python



Python


In this article, we show how to safely delete files and folders using the send2trash module in Python.

In Python, we can delete files and directories through the os.unlink() function (for files), the os.rmdir() function (for empty directories), and the shutil.rmtree() for directories (that have contents in them).

However, all of these methods permanently delete files once the deletion occurs. This makes it dangerous if there were any accidental deletions performed. This is because these deletions cannot be undone.

There is a safer way for deletions to be performed.

This is with the send2trash module. With the send2trash module, files and/or folders are deleted and sent to the computer's recycle bin. Therefore, if any mistakes were made in the deletion process, they can be undone by using restore in the recycle bin.

Before you can use the send2trash module, you must install the module.

This is done through the line, pip install send2trash.

If you don't understand how to install modules using pip, see How to Install Django. All you have to do is to instead of putting django, as the article states, you would put send2trash. Note, that the tutorial is specific to windows computers. But you just have to modify it slightly for Mac and Linux computers. It's the same concept.

So, once you have installed the send2trash module, then we're ready to continue.

So to delete a file with the send2trash module, all you have to do is use the line, send2trash.send2trash(file_to_delete).

This is shown below.



So, first, we must import the send2trash module.

After this, we use the line, send2trash.send2trash() function to delete a file. Inside of this function, we specify the path to the file. If the file is in the current working directory, then you just have to simply put the filename.

You can do the same with directories, just as with files. Nothing changes.

The code below safely deletes the PythonProjects2 directory.



So, after this is run, the PythonProjects2 directory will be deleted.


Related Resources



HTML Comment Box is loading comments...