How can I delete a file or folder in Python?
Interview Questions practice on Codemia
Over 8,000 real interview questions from top companies, searchable by company and role.
Introduction
Deleting files and directories in Python is straightforward once you separate three cases: deleting one file, deleting an empty directory, and deleting a directory tree. Each case uses a different API, and choosing the wrong one usually raises an exception instead of doing something helpful.
For modern Python code, pathlib is usually the clearest option, while os and shutil remain important for lower-level or recursive operations. The safest solution depends on whether you want to fail loudly, ignore missing paths, or remove everything below a directory.
Delete A Single File
For one file, use Path.unlink() or os.remove().
The same operation with os.remove() looks like this:
Both approaches remove a file. Neither will delete a directory.
Delete An Empty Directory
If the target is an empty directory, use rmdir().
You can also use os.rmdir(). The critical rule is that rmdir() only works when the directory contains nothing. If files or subdirectories remain inside, Python raises an error.
Delete A Non-Empty Directory Tree
If you want to remove a directory and everything below it, use shutil.rmtree().
This is intentionally powerful. It removes all files and subdirectories recursively, so it is the method to use for cache folders, generated output, or disposable working directories.
Prefer pathlib For Readable Code
pathlib often makes deletion code easier to read because path operations stay attached to the path object itself.
That style scales well when you are creating, inspecting, and deleting paths in the same function.
Handle Missing Paths Deliberately
You do not always need an existence check before deletion. In cleanup code, it is often better to attempt the operation and catch the specific exception.
This avoids a race condition where the file exists during the check but disappears before the deletion call. In concurrent systems, exception-based handling is often more reliable than a separate exists() check.
One Helper For Files And Folders
If you want a utility function that handles both files and directories, keep the behavior explicit.
That helper treats any directory as recursive deletion. If that is too aggressive for your use case, swap in path.rmdir() and let non-empty directories fail instead.
Common Pitfalls
- Calling
unlink()oros.remove()on a directory. - Using
rmdir()on a directory that still contains files. - Running
shutil.rmtree()without realizing it deletes the whole tree. - Assuming an
exists()check guarantees the path will still be there a moment later. - Mixing string-based paths everywhere when
pathlibwould make the code clearer.
Summary
- Use
Path.unlink()oros.remove()to delete a file. - Use
Path.rmdir()oros.rmdir()only for empty directories. - Use
shutil.rmtree()to remove a non-empty directory tree. - Prefer
pathlibin new code because path handling is easier to read. - In cleanup code, catching
FileNotFoundErroris often safer than a separate existence check.
Related reading
- How do I check if a list is empty?
- How do I clone a list so that it doesn't change unexpectedly after assignment?
- How do I concatenate two lists in Python?
- How do I make a flat list out of a list of lists?
- How do I put a time delay in a Python script?
- How do I split a list into equally-sized chunks?
- How slicing in Python works
- "Least Astonishment" and the Mutable Default Argument
.png&w=3840&q=75)
Tackling System Design Interview Problems
A short course that equips you with the skills to approach system design interviews methodically.
Start the free courseTrack what you have practised
A free account saves your progress, solutions and study plan across every problem on Codemia.
Interview Questions practice on Codemia
Over 8,000 real interview questions from top companies, searchable by company and role.