How can I delete a file or folder in Python?
To swiftly remove a file, utilize os.remove('file.txt')
. For obliterating an empty directory, use os.rmdir('empty_dir/')
. To eradicate an entire directory tree along with its subdirectories and files, turn to shutil.rmtree('dir/')
. For practicality, here's the juice:
Quick and smooth file deletion
Running Python 3.8+? Deleting files has never been safer. Utilize pathlib.Path.unlink(missing_ok=True)
to safely remove files and steer clear of a FileNotFoundError
if the file is a ghost.
Delete per pattern: The Python way
Use Python's glob
module to mass delete files based on specific patterns or extensions. Combined with os.remove()
, it's spring cleaning made easy:
Visulisation
Think of handling files and folders as keeping a garden tidy, with flowers representing files, and bushes standing for folders:
Got a flower (file) you do not want? Time to pluck:
Bumped into a bush (folder)? Uproot it, along with everything in it:
A tidy digital garden 🌐 is one that is free from unwanted files (flowers) and folders (bushes)!
Uprooting a dense bush (a non-empty folder)
Want to remove a directory but it is crammed with files? os.rmdir()
chucking OSError
at you? Don't fret! shutil.rmtree()
is a one-stop solution that clears the directory before erasing it:
Dealing with divas and permissions
Occasionally, a file or folder cannot be deleted on account of insufficient permissions. Using try-except
can elegantly maneuver these speed bumps:
Unmasking the file path
Not sure if a path points to a file, directory, or a symlink? Check before hitting delete. A stitch in time saves nine:
Deleting many files: One fell swoop
Batch deletion is both seamless and effective. Here's how you can round up and dispose of multiple files:
Was this article helpful?