Master Python file and folder deletion using os.remove(), os.rmdir(), shutil.rmtree(), and pathlib. This guide shows safe and cross-platform methods.
Scalable, Secure, and High-Performance Solutions for Your Business.
Python has built in ways to delete files and folders using the os and shutil modules. Whether you’re removing a single file or an entire directory tree, these tools let you do it safely and cross platform.
Removes a specific file from your system using os.remove().
import os
file_path = “example.txt”
if os.path.exists(file_path):
os.remove(file_path)
print(“File deleted successfully.”)
else:
print(“File not found.”)
Note: Always check if the file exists before deleting to avoid FileNotFoundError.
Deletes an empty directory using os.rmdir().
import os
folder_path = “empty_folder”
if os.path.exists(folder_path):
os.rmdir(folder_path)
print(“Folder deleted successfully.”)
else:
print(“Folder not found.”)
Note: os.rmdir() only works if the folder is empty.
It will Remove a folder and everything inside using shutil.rmtree().
import shutil
folder_path = “folder_with_files”
shutil.rmtree(folder_path)
print(“Folder and all contents deleted.”)
Note: Use this with caution; it will delete everything in the directory.
Also Read: How Much Does It Cost To Build A Web App With Python in 2025?
Python’s pathlib module is a more modern, object oriented way to work with files and directories.
from pathlib import Path
file = Path(“example.txt”)
if file.exists():
file.unlink() # Removes the file
To remove a folder (even with contents) you can combine pathlib with shutil:
from pathlib import Pathimport shutil
dir_path = Path(“my_folder”)
if dir_path.exists() and dir_path.is_dir():
shutil.rmtree(dir_path)
pathlib makes your code cleaner and easier to read, especially when working with paths across different operating systems.
eSparkBiz is rated 4.9 Stars
Real People, Real Stories
See why 300+ startups & enterprises trust eSparkBiz with their software outsourcingYou can copy files in python using the shutil module which provides high level file and collection of files operations. You can also combine it…
The demand for Python skills in Europe is growing as companies adopt AI driven solutions, enterprise platforms and interactive web applications. Businesses need developers who…
Amazon CloudWatch allows you to run log insights queries using the logs client in Boto3. Below is a step by step guide to querying logs…
Let’s discuss how our dedicated experts can help.