Delete a file or folder in Python

Python provides the os.remove and os.unlink functions to delete files and os.rmdir and shutil.rmtree to delete directories. Python 3.4+ offers an additional module called pathlib and two functions called unlink (deletes a file or symbolic link) and rmtree (deletes an empty directory).

Delete a file

The easiest way to delete a file is by using the os.remove function.

These two lines of code are going to remove a file in the working directory.

If the file doesn’t exist, the code will return an error.

Delete a file if exists

Before we delete a file, is a good practice to check whether it exists.

After this modification, you can remove the file if it exists, otherwise, the message will be printed to the console.

You can also use try and except to handle an exception.

Now, when the file is present, this code will remove it without displaying any message, but when it can’t find the file it will display an error message, instead of returning an error as it did before.

Delete a file with os.unlink

You can easily replace os.remove with os.unlink and the code will remove the file if exists and return the same messages if it doesn’t exist.

So what’s the difference between them?

Windows users are used to remove and Unix users are used to unlink.

Delete all files in a directory

In directory delete_all_files there are three files: text, word, and jpg.

This code will delete all these files.

The problem starts when there is another directory (even empty) inside the directory. Now, the code will return an error message:

In order to get rid of this error, we have to detect whether an object is a file or directory. If it’s the directory we skip it, otherwise, we will use remove.

The os.path.isdir function will help us with this task.

Now, if the program finds any kind of directory, it will skip it.

Delete an empty directory

The following code deletes a directory, only if it’s empty, otherwise it returns an error.

Delete a directory with all its contents

Be careful when you use this code because it removes a directory even if the directory contains other files and directories.

Delete all files in a directory recursively

This code is going to remove all files recursively. This means that it will walk through every directory to find files and remove them, but keep the directory tree intact.

Delete files and directories from a directory

The last code removed all files but kept directories. This time we are going to remove the files first, and then, when the directories are empty, we are going to use shutil.rmtree to remove remaining directories, but not the top one.