Deleting Files and Directories (remove, rmdir)

๐Ÿท๏ธ Operating System and System Operations / The os Module

When working with files and folders in Python, you'll often need to clean up temporary files, remove old logs, or delete empty directories. The os module provides two simple functions for this: os.remove() for files and os.rmdir() for empty directories. These are the basic building blocks for file cleanup operations.


โš™๏ธ Understanding the Two Functions

  • os.remove(path) โ€“ Deletes a single file at the specified path. If the file does not exist, Python raises a FileNotFoundError.
  • os.rmdir(path) โ€“ Deletes an empty directory at the specified path. If the directory contains any files or subdirectories, Python raises an OSError (specifically "Directory not empty").

Both functions are permanent operations โ€” there is no recycle bin or undo. Once deleted, the data is gone.


๐Ÿ› ๏ธ Basic Usage Examples

Deleting a file: - Import the os module: import os - Call os.remove("old_log.txt") to delete a file named old_log.txt in the current directory. - For a full path: os.remove("/tmp/temp_data.csv")

Deleting an empty directory: - Call os.rmdir("empty_folder") to delete a folder named empty_folder in the current directory. - For a full path: os.rmdir("/home/user/old_backup")


๐Ÿ•ต๏ธ Checking Before Deleting

It is good practice to check if a file or directory exists before attempting to delete it. This prevents your script from crashing with an error.

Check if a file exists before removing: - Use os.path.exists("myfile.txt") which returns True or False - Combine with a conditional: if os.path.exists("myfile.txt"): os.remove("myfile.txt")

Check if a directory exists before removing: - Use os.path.isdir("myfolder") which returns True only if the path is a directory - Example: if os.path.isdir("myfolder"): os.rmdir("myfolder")


๐Ÿ“Š Comparing os.remove() and os.rmdir()

Feature os.remove() os.rmdir()
What it deletes A single file An empty directory
Error if not found FileNotFoundError FileNotFoundError
Error if not empty N/A (files don't have contents) OSError: Directory not empty
Can delete non-empty Yes (files are always "empty") No โ€” only empty directories
Common use case Removing old log files, temp files Cleaning up empty folders after file deletion

๐Ÿงช Practical Example: Cleaning Up a Temp Folder

Imagine you have a temporary folder where you store generated reports. After processing, you want to delete each report file and then remove the empty folder.

Step-by-step approach: - Define the folder path: folder = "/tmp/reports" - List all files in the folder: files = os.listdir(folder) - Loop through each file: for file in files: - Build the full file path: file_path = os.path.join(folder, file) - Delete the file: os.remove(file_path) - After the loop, delete the now-empty folder: os.rmdir(folder)

This pattern is very common in automation scripts that generate and clean up temporary data.


โš ๏ธ Important Warnings and Best Practices

  • Deleted files cannot be recovered โ€” always double-check the path before calling remove or rmdir.
  • Use try/except blocks to handle errors gracefully instead of letting your script crash.
  • Never delete files based on user input without validation โ€” this is a security risk.
  • For non-empty directories, you need shutil.rmtree() (covered in a separate topic), not os.rmdir().
  • On Windows, you may encounter permission errors if the file is open in another program.

๐Ÿ” Error Handling Example

A safe way to delete a file with error handling:

  • Use a try block: try: os.remove("important.txt")
  • Catch the FileNotFoundError: except FileNotFoundError: print("File not found, skipping")
  • Catch other OSError issues: except OSError: print("Permission denied or other error")

This pattern ensures your script continues running even if something goes wrong.


๐Ÿ“ Summary

  • os.remove() deletes a single file โ€” use it to clean up individual files.
  • os.rmdir() deletes an empty directory โ€” use it after removing all files inside.
  • Always check existence with os.path.exists() or os.path.isdir() before deleting.
  • Wrap deletion calls in try/except blocks to handle errors without crashing.
  • For deleting entire folder trees (non-empty directories), look into shutil.rmtree() in a later topic.

Mastering these two functions gives you precise control over file and directory cleanup in your Python scripts.


The os.remove() and os.rmdir() functions delete files and empty directories from the filesystem, respectively.

๐Ÿ“ Example 1: Deleting a single file with os.remove()

This example shows how to delete a single file by specifying its path.

import os

# Create a test file first
with open("temp_file.txt", "w") as f:
    f.write("This file will be deleted.")

# Delete the file
os.remove("temp_file.txt")

# Check if file still exists
file_exists = os.path.exists("temp_file.txt")
print(file_exists)

๐Ÿ“ค Output: False


๐Ÿ“ Example 2: Deleting an empty directory with os.rmdir()

This example demonstrates how to remove an empty directory using os.rmdir().

import os

# Create an empty directory first
os.mkdir("empty_folder")

# Delete the empty directory
os.rmdir("empty_folder")

# Check if directory still exists
dir_exists = os.path.exists("empty_folder")
print(dir_exists)

๐Ÿ“ค Output: False


๐Ÿ“ Example 3: Handling errors when file does not exist

This example shows how to safely attempt deletion when the target file might not exist.

import os

file_path = "non_existent_file.txt"

# Try to delete a file that doesn't exist
try:
    os.remove(file_path)
    print("File deleted successfully")
except FileNotFoundError:
    print("File not found - nothing to delete")

๐Ÿ“ค Output: File not found - nothing to delete


๐Ÿ“ Example 4: Deleting all files in a directory

This example demonstrates how to remove every file inside a directory while keeping the directory itself.

import os

# Create a directory with test files
os.mkdir("log_files")
for i in range(3):
    with open(f"log_files/log_{i}.txt", "w") as f:
        f.write(f"Log entry {i}")

# List all files in the directory
files = os.listdir("log_files")
print("Files before deletion:", files)

# Delete each file
for file_name in files:
    file_path = os.path.join("log_files", file_name)
    os.remove(file_path)

# Verify all files are gone
remaining_files = os.listdir("log_files")
print("Files after deletion:", remaining_files)

# Clean up the empty directory
os.rmdir("log_files")

๐Ÿ“ค Output: Files before deletion: ['log_0.txt', 'log_1.txt', 'log_2.txt']
๐Ÿ“ค Output: Files after deletion: []


๐Ÿ“ Example 5: Safely deleting a file with existence check

This example shows a practical pattern for deleting a file only if it exists.

import os

# Create a temporary file
with open("config_backup.txt", "w") as f:
    f.write("backup configuration data")

file_to_delete = "config_backup.txt"

# Check existence before deletion
if os.path.exists(file_to_delete):
    os.remove(file_to_delete)
    print(f"Deleted: {file_to_delete}")
else:
    print(f"File not found: {file_to_delete}")

# Try deleting again (file is already gone)
if os.path.exists(file_to_delete):
    os.remove(file_to_delete)
    print(f"Deleted: {file_to_delete}")
else:
    print(f"File not found: {file_to_delete}")

๐Ÿ“ค Output: Deleted: config_backup.txt
๐Ÿ“ค Output: File not found: config_backup.txt


๐Ÿ“ Example 6: Removing a non-empty directory (using shutil)

This example demonstrates that os.rmdir() fails on non-empty directories, and shows the alternative using shutil.

import os
import shutil

# Create a directory with files inside
os.mkdir("project_data")
with open("project_data/data.txt", "w") as f:
    f.write("important data")

# Attempt to remove non-empty directory with os.rmdir
try:
    os.rmdir("project_data")
    print("Directory removed with rmdir")
except OSError as e:
    print(f"os.rmdir failed: {e}")
    print("Using shutil.rmtree instead...")
    shutil.rmtree("project_data")
    print("Directory removed with shutil.rmtree")

# Verify deletion
dir_exists = os.path.exists("project_data")
print(f"Directory exists: {dir_exists}")

๐Ÿ“ค Output: os.rmdir failed: [Errno 39] Directory not empty: 'project_data'
๐Ÿ“ค Output: Using shutil.rmtree instead...
๐Ÿ“ค Output: Directory removed with shutil.rmtree
๐Ÿ“ค Output: Directory exists: False


Comparison Table

Function Purpose Works on Requires empty? Removes contents?
os.remove() Delete a file Files only N/A N/A
os.rmdir() Delete a directory Directories only Yes No
shutil.rmtree() Delete a directory tree Directories only No Yes

When working with files and folders in Python, you'll often need to clean up temporary files, remove old logs, or delete empty directories. The os module provides two simple functions for this: os.remove() for files and os.rmdir() for empty directories. These are the basic building blocks for file cleanup operations.


โš™๏ธ Understanding the Two Functions

  • os.remove(path) โ€“ Deletes a single file at the specified path. If the file does not exist, Python raises a FileNotFoundError.
  • os.rmdir(path) โ€“ Deletes an empty directory at the specified path. If the directory contains any files or subdirectories, Python raises an OSError (specifically "Directory not empty").

Both functions are permanent operations โ€” there is no recycle bin or undo. Once deleted, the data is gone.


๐Ÿ› ๏ธ Basic Usage Examples

Deleting a file: - Import the os module: import os - Call os.remove("old_log.txt") to delete a file named old_log.txt in the current directory. - For a full path: os.remove("/tmp/temp_data.csv")

Deleting an empty directory: - Call os.rmdir("empty_folder") to delete a folder named empty_folder in the current directory. - For a full path: os.rmdir("/home/user/old_backup")


๐Ÿ•ต๏ธ Checking Before Deleting

It is good practice to check if a file or directory exists before attempting to delete it. This prevents your script from crashing with an error.

Check if a file exists before removing: - Use os.path.exists("myfile.txt") which returns True or False - Combine with a conditional: if os.path.exists("myfile.txt"): os.remove("myfile.txt")

Check if a directory exists before removing: - Use os.path.isdir("myfolder") which returns True only if the path is a directory - Example: if os.path.isdir("myfolder"): os.rmdir("myfolder")


๐Ÿ“Š Comparing os.remove() and os.rmdir()

Feature os.remove() os.rmdir()
What it deletes A single file An empty directory
Error if not found FileNotFoundError FileNotFoundError
Error if not empty N/A (files don't have contents) OSError: Directory not empty
Can delete non-empty Yes (files are always "empty") No โ€” only empty directories
Common use case Removing old log files, temp files Cleaning up empty folders after file deletion

๐Ÿงช Practical Example: Cleaning Up a Temp Folder

Imagine you have a temporary folder where you store generated reports. After processing, you want to delete each report file and then remove the empty folder.

Step-by-step approach: - Define the folder path: folder = "/tmp/reports" - List all files in the folder: files = os.listdir(folder) - Loop through each file: for file in files: - Build the full file path: file_path = os.path.join(folder, file) - Delete the file: os.remove(file_path) - After the loop, delete the now-empty folder: os.rmdir(folder)

This pattern is very common in automation scripts that generate and clean up temporary data.


โš ๏ธ Important Warnings and Best Practices

  • Deleted files cannot be recovered โ€” always double-check the path before calling remove or rmdir.
  • Use try/except blocks to handle errors gracefully instead of letting your script crash.
  • Never delete files based on user input without validation โ€” this is a security risk.
  • For non-empty directories, you need shutil.rmtree() (covered in a separate topic), not os.rmdir().
  • On Windows, you may encounter permission errors if the file is open in another program.

๐Ÿ” Error Handling Example

A safe way to delete a file with error handling:

  • Use a try block: try: os.remove("important.txt")
  • Catch the FileNotFoundError: except FileNotFoundError: print("File not found, skipping")
  • Catch other OSError issues: except OSError: print("Permission denied or other error")

This pattern ensures your script continues running even if something goes wrong.


๐Ÿ“ Summary

  • os.remove() deletes a single file โ€” use it to clean up individual files.
  • os.rmdir() deletes an empty directory โ€” use it after removing all files inside.
  • Always check existence with os.path.exists() or os.path.isdir() before deleting.
  • Wrap deletion calls in try/except blocks to handle errors without crashing.
  • For deleting entire folder trees (non-empty directories), look into shutil.rmtree() in a later topic.

Mastering these two functions gives you precise control over file and directory cleanup in your Python scripts.

Interactive Views

You are currently in ๐Ÿ“š All-in-One mode. Use the tabs at the top to switch to ๐Ÿ“– Theory Only or ๐Ÿ’ป Code Only views.

The os.remove() and os.rmdir() functions delete files and empty directories from the filesystem, respectively.

๐Ÿ“ Example 1: Deleting a single file with os.remove()

This example shows how to delete a single file by specifying its path.

import os

# Create a test file first
with open("temp_file.txt", "w") as f:
    f.write("This file will be deleted.")

# Delete the file
os.remove("temp_file.txt")

# Check if file still exists
file_exists = os.path.exists("temp_file.txt")
print(file_exists)

๐Ÿ“ค Output: False


๐Ÿ“ Example 2: Deleting an empty directory with os.rmdir()

This example demonstrates how to remove an empty directory using os.rmdir().

import os

# Create an empty directory first
os.mkdir("empty_folder")

# Delete the empty directory
os.rmdir("empty_folder")

# Check if directory still exists
dir_exists = os.path.exists("empty_folder")
print(dir_exists)

๐Ÿ“ค Output: False


๐Ÿ“ Example 3: Handling errors when file does not exist

This example shows how to safely attempt deletion when the target file might not exist.

import os

file_path = "non_existent_file.txt"

# Try to delete a file that doesn't exist
try:
    os.remove(file_path)
    print("File deleted successfully")
except FileNotFoundError:
    print("File not found - nothing to delete")

๐Ÿ“ค Output: File not found - nothing to delete


๐Ÿ“ Example 4: Deleting all files in a directory

This example demonstrates how to remove every file inside a directory while keeping the directory itself.

import os

# Create a directory with test files
os.mkdir("log_files")
for i in range(3):
    with open(f"log_files/log_{i}.txt", "w") as f:
        f.write(f"Log entry {i}")

# List all files in the directory
files = os.listdir("log_files")
print("Files before deletion:", files)

# Delete each file
for file_name in files:
    file_path = os.path.join("log_files", file_name)
    os.remove(file_path)

# Verify all files are gone
remaining_files = os.listdir("log_files")
print("Files after deletion:", remaining_files)

# Clean up the empty directory
os.rmdir("log_files")

๐Ÿ“ค Output: Files before deletion: ['log_0.txt', 'log_1.txt', 'log_2.txt']
๐Ÿ“ค Output: Files after deletion: []


๐Ÿ“ Example 5: Safely deleting a file with existence check

This example shows a practical pattern for deleting a file only if it exists.

import os

# Create a temporary file
with open("config_backup.txt", "w") as f:
    f.write("backup configuration data")

file_to_delete = "config_backup.txt"

# Check existence before deletion
if os.path.exists(file_to_delete):
    os.remove(file_to_delete)
    print(f"Deleted: {file_to_delete}")
else:
    print(f"File not found: {file_to_delete}")

# Try deleting again (file is already gone)
if os.path.exists(file_to_delete):
    os.remove(file_to_delete)
    print(f"Deleted: {file_to_delete}")
else:
    print(f"File not found: {file_to_delete}")

๐Ÿ“ค Output: Deleted: config_backup.txt
๐Ÿ“ค Output: File not found: config_backup.txt


๐Ÿ“ Example 6: Removing a non-empty directory (using shutil)

This example demonstrates that os.rmdir() fails on non-empty directories, and shows the alternative using shutil.

import os
import shutil

# Create a directory with files inside
os.mkdir("project_data")
with open("project_data/data.txt", "w") as f:
    f.write("important data")

# Attempt to remove non-empty directory with os.rmdir
try:
    os.rmdir("project_data")
    print("Directory removed with rmdir")
except OSError as e:
    print(f"os.rmdir failed: {e}")
    print("Using shutil.rmtree instead...")
    shutil.rmtree("project_data")
    print("Directory removed with shutil.rmtree")

# Verify deletion
dir_exists = os.path.exists("project_data")
print(f"Directory exists: {dir_exists}")

๐Ÿ“ค Output: os.rmdir failed: [Errno 39] Directory not empty: 'project_data'
๐Ÿ“ค Output: Using shutil.rmtree instead...
๐Ÿ“ค Output: Directory removed with shutil.rmtree
๐Ÿ“ค Output: Directory exists: False


Comparison Table

Function Purpose Works on Requires empty? Removes contents?
os.remove() Delete a file Files only N/A N/A
os.rmdir() Delete a directory Directories only Yes No
shutil.rmtree() Delete a directory tree Directories only No Yes