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.
import os os.remove("myfile.txt")
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.
FileNotFoundError: [WinError 2] The system cannot find the file specified: 'myfile.txt'
Delete a file if exists
Before we delete a file, is a good practice to check whether it exists.
import os myfile = "myfile.txt" if os.path.exists(myfile): os.remove(myfile) else: print("Can't remove the file, because it doesn't 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.
import os myfile = "myfile.txt" try: os.remove(myfile) except Exception as e: print(e)
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.
[WinError 2] The system cannot find the file specified: 'myfile.txt'
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.
import os os.unlink("myfile.txt")
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.
import os import glob all_files = glob.glob(r'D:\delete_all_files\*') for f in all_files: os.remove(f)
The problem starts when there is another directory (even empty) inside the directory. Now, the code will return an error message:
PermissionError: [WinError 5] Access is denied: 'D:\\delete_all_files\\not_empty_file'
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.
import os import glob all_files = glob.glob(r'D:\delete_all_files\*') for f in all_files: if not os.path.isdir(f): os.remove(f)
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.
import os my_dir = r'D:\delete_all_files' if os.path.isdir(my_dir): os.rmdir(my_dir)
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.
import shutil shutil.rmtree(r'D:\delete_all_files')
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.
import os for root, dirs, files in os.walk(r'D:\delete_all_files'): for name in files: os.remove(os.path.join(root, name))
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.
import os import shutil for root, dirs, files in os.walk(r'D:\delete_all_files'): for f in files: os.unlink(os.path.join(root, f)) for d in dirs: shutil.rmtree(os.path.join(root, d))