How to Delete a File or Folder in Python?

Master Python file and folder deletion using os.remove(), os.rmdir(), shutil.rmtree(), and pathlib. This guide shows safe and cross-platform methods.

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.
Related

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…

28 Oct, 2025

The Kalman Filter is an efficient recursive algorithm used to estimate the state of a system from noisy measurements. In computer vision, it’s commonly used…

21 Oct, 2025

Printing exceptions in python helps to debug issues by giving clear information about what went wrong and where. You can access the exception message or…

15 Oct, 2025