How to delete files and folders in Python
Delete files/folders in Python using os and shutil, and pathlib.
Both libraries come under standard python packages, so there’s no installation required. Let’s dive straight in.
Deletion of files:¶
This is the most straightforward way to delete a file from the system,
file_path must be a path-like python object. The behaviour of deletion operation differs based on Operation System.
On Windows a file can not be deleted until it is being used by another application. On the other hand, on Linux the file object is deleted but data on disk is not erased until the application using it releases the lock.
import os os.remove("/home/user/Documents/notes.txt")
Deletes a file or symlink. If
missing_ok is True then FileNotFoundError will be suppressed. In Linux based systems, symlinks can be of same name as target file, whereas in Windows, shortcuts have a .lnk extension.
import pathlib path = pathlib.Path("/home/user/Desktop/sample_pdf.pdf") path.unlink()
Deletion of folders:¶
Working of this function is similar to rmdir in Linux.
directory_path should be a python path-like object. If the directory specified in the path is not empty an error will be raised, implying that only empty directories can be deleted.
import os os.rmdir("/home/user/Desktop/Images")
Path.rmdir() is an alternative to
os.rmdir(). Under the hood pathlib extends
os.rmdir() functionality. Directory to be deleted must be empty.
import pathlib path = pathlib.Path("/home/user/Desktop/Images") # create a path object first, rmdir() does not take any arguments path.rmdir()
shutil is associated with file operations and also includes a function that can be used to delete a directory and all of its contents recursively. It is similar to Linux rm -rf command. The directory path provided must not be a symlink.
import shutil shutil.rmdir("/home/user/Desktop/Images")
FREE VS Code / PyCharm Extensions I Use
✅ Write cleaner code with Sourcery, instant refactoring suggestions: Link** This is an affiliate link. By clicking on it you will not have any additional costs. Instead, you will support my project. Thank you! 🙏