Explain Codes LogoExplain Codes Logo

How can I delete a file or folder in Python?

python
file-deletion
pathlib
file-handling
Alex KataevbyAlex Kataev·Sep 19, 2024
TLDR

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:

import os, shutil os.remove('file.txt') # Delete file os.rmdir('empty_dir/') # Delete empty directory shutil.rmtree('dir/') # Delete directory tree

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.

from pathlib import Path file_path = Path('file.txt') file_path.unlink(missing_ok=True) # Ghostbusting, the Python way :)

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:

import glob, os for filename in glob.glob('*.txt'): os.remove(filename) # Away with all .txt files

Visulisation

Think of handling files and folders as keeping a garden tidy, with flowers representing files, and bushes standing for folders:

Garden Before: [🌸, 🌼, 🌻, 🌺, 🌷, 🌳(folder)]

Got a flower (file) you do not want? Time to pluck:

os.remove('flower.txt') # Bye-bye 🌷.
Garden After: [🌸, 🌼, 🌻, 🌺, 🌳(folder)]

Bumped into a bush (folder)? Uproot it, along with everything in it:

shutil.rmtree('bush/') # Clears 🌳 and all its dwellers.
Garden Pruned: [🌸, 🌼, 🌻, 🌺]

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:

shutil.rmtree('non_empty_dir/', ignore_errors=True) # Sayonara without tantrums

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:

try: os.remove('protected_file.txt') except PermissionError as e: print("Being denied permission: ", e, " . 😔")

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:

import os path = 'mystery_object' if os.path.isfile(path): os.remove(path) elif os.path.isdir(path): os.rmdir(path) elif os.path.islink(path): os.unlink(path)

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:

files_to_delete = [f for f in os.listdir('target_dir/') if f.endswith('.log')] for f in files_to_delete: os.remove(os.path.join('target_dir/', f)) # ".log" files? Not on my watch!