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.
Python code
31 linesimport 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
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
- Use `os.walk()` with `os.remove()` for Python versions before 3.4
- 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
More from Files & data
- Build a Command-Line To-Do List Application with Data Persistence in Python easy
- Compare Two Folder Structures and Find Differences in Python easy
- Compress and Extract ZIP Files Programmatically in Python easy
- Convert CSV Files to JSON in Python easy
- Convert Image to ASCII Art in Python medium
- Create a Personal Knowledge Base That Searches Notes Instantly in Python easy
Keep learning
Related tutorials and quizzes for this topic.