Maintenance

Site is under maintenance — quizzes are still available.

Go to quizzes
Sponsored Reserved space — layout preview until AdSense is connected

Build a Python Script That Detects and Deletes Empty Files Across Folders

A Python script that recursively finds and removes all zero-byte files across nested directories, returning a list of deleted paths.

Easy Python 3.9+ Jun 27, 2026 Files & data 1 views 0 copies

Python code

31 lines
Python 3.9+
import os
from pathlib import Path

def find_and_delete_empty_files(root_dir: str) -> list:
    """Find and delete all empty files under root_dir. Returns list of deleted paths."""
    deleted = []
    for file_path in Path(root_dir).rglob('*'):
        if file_path.is_file() and file_path.stat().st_size == 0:
            file_path.unlink()
            deleted.append(str(file_path))
    return deleted

if __name__ == "__main__":
    # Create test directory structure with empty and non-empty files
    test_dir = Path("test_empty_cleanup")
    test_dir.mkdir(exist_ok=True)
    (test_dir / "empty1.txt").touch()
    (test_dir / "important.txt").write_text("Important data")
    (test_dir / "subfolder").mkdir(exist_ok=True)
    (test_dir / "subfolder" / "empty2.log").touch()
    (test_dir / "subfolder" / "data.csv").write_text("a,b,c\n1,2,3")

    # Run the deletion
    result = find_and_delete_empty_files("test_empty_cleanup")
    print(f"Deleted {len(result)} empty files:")
    for path in result:
        print(f"  - {path}")

    # Cleanup test directory
    import shutil
    shutil.rmtree(test_dir)

Output

stdout
Deleted 2 empty files:
  - test_empty_cleanup/empty1.txt
  - test_empty_cleanup/subfolder/empty2.log

How it works

The script uses Path.rglob('*') to walk through every file and subdirectory recursively. For each file, file_path.stat().st_size checks if the file size is exactly zero bytes. If so, file_path.unlink() removes the file immediately. The function collects and returns the paths of all deleted files, which is useful for logging or reporting.

Common mistakes

  • Checking `os.path.getsize()` on directories which raises an error
  • Forgetting to filter `.is_file()` before checking size, causing errors on directories
  • Not handling permission errors when calling `.unlink()` on protected files

Variations

  1. Use `os.walk()` with `os.remove()` for Python versions before 3.4
  2. Add a dry run mode using `--dry-run` argument to preview without deleting

Real-world use cases

  • Cleaning up stale empty report files generated by cron jobs in a log directory.
  • Removing placeholder files created by faulty upload workflows in a cloud storage sync folder.
  • Preparing a dataset by stripping empty text files before running an ETL pipeline.

Sponsored

Sponsored Reserved space — layout preview until AdSense is connected

Run this sample

Open the browser IDE to tweak the example and see results without installing anything.

Open editor

More from Files & data

Related tutorials and quizzes for this topic.