How to Filter Files by Extension and Size in Python

Use pathlib to list files in a directory, filter by extension or minimum size, and return matching names or (name, size) pairs.

Easy Python 3.6+ Aug 9, 2026 Files & data 13 views 0 copies

Python code

28 lines
Python 3.6+
from pathlib import Path

def filter_files_by_extension(directory: str, extension: str) -> list:
    """Return a list of file names in directory with the given extension."""
    path = Path(directory)
    return [f.name for f in path.iterdir() if f.is_file() and f.suffix == extension]

def filter_files_by_size(directory: str, min_size: int = 0) -> list:
    """Return a list of (name, size) for files larger than min_size bytes."""
    path = Path(directory)
    return [(f.name, f.stat().st_size) for f in path.iterdir() if f.is_file() and f.stat().st_size > min_size]

if __name__ == "__main__":
    # Example: create a temp dir with sample files for demonstration
    import tempfile, os

    with tempfile.TemporaryDirectory() as tmpdir:
        for name in ["a.txt", "b.py", "c.md", "d.txt"]:
            Path(tmpdir, name).write_text("x" * 50)  # 50 bytes each

        # Create one larger file
        Path(tmpdir, "big.log").write_text("y" * 200)

        txt_files = filter_files_by_extension(tmpdir, ".txt")
        print("Text files:", txt_files)

        files_over_100_bytes = filter_files_by_size(tmpdir, min_size=100)
        print("Files > 100 bytes:", files_over_100_bytes)

Output

stdout
Text files: ['a.txt', 'd.txt']
Files > 100 bytes: [('big.log', 200)]

How it works

Path.iterdir() yields paths for every entry in the directory, and checking f.is_file() ensures we only keep actual files, not subdirectories. f.suffix returns the file extension including the dot, so comparing with .txt works as expected. For size filtering, f.stat().st_size gives the file size in bytes, and the list comprehension filters to files larger than min_size. Using a temporary directory inside the __main__ block keeps the example self-contained and avoids cluttering the current folder.

Common mistakes

  • Forgetting to check `f.is_file()`, which would include subdirectories.
  • Mismatching the extension string (e.g., 'txt' instead of '.txt').
  • Assuming `f.suffix` is case-sensitive; '.TXT' won't match '.txt'.

Variations

  1. Use `path.glob(f'*{extension}')` to filter by extension more directly.
  2. Use `os.listdir()` with `os.path.isfile()` and `os.path.splitext()` for a more procedural approach.

Real-world use cases

  • Scanning a download folder to list only text or CSV files before processing.
  • Cleaning up old log files by size to free disk space in a maintenance script.
  • Creating a file inventory for an ETL job that needs to pick up files above a certain size threshold.

Sponsored

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.