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.
Method 1: Delete a File
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.
Method 2: Delete an Empty Folder
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.
Method 3: Delete a Folder with Contents
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?
Method 4: Use pathlib (Modern Alternative)
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.
Tip
- Always backup or double check the path before using rmtree().
- Use os.path.exists() or Path.exists() (from pathlib) to safely check paths.
- On Windows, make sure the file/folder isn’t open in another program.