How to List File Information in a Directory with Python

A helper that walks a directory and returns each file's name, size, and extension as a list of dictionaries.

Easy Python 3.9+ Aug 9, 2026 Files & data 12 views 0 copies

Python code

26 lines
Python 3.9+
from pathlib import Path


def get_files_data(directory: str) -> list[dict]:
    """Return basic info about all files in a directory."""
    files = []
    for path in Path(directory).iterdir():
        if path.is_file():
            files.append({
                "name": path.name,
                "size": path.stat().st_size,
                "extension": path.suffix,
            })
    return files


if __name__ == "__main__":
    import tempfile
    import os

    with tempfile.TemporaryDirectory() as tmp_dir:
        for fname, content in [("notes.txt", "hello"), ("data.csv", "1,2,3"), ("script.py", "print('hi')")]:
            Path(tmp_dir, fname).write_text(content)
        result = get_files_data(tmp_dir)
        for file_info in sorted(result, key=lambda f: f["name"]):
            print(file_info)

Output

stdout
{'name': 'data.csv', 'size': 5, 'extension': '.csv'}
{'name': 'notes.txt', 'size': 5, 'extension': '.txt'}
{'name': 'script.py', 'size': 13, 'extension': '.py'}

How it works

This function uses Path.iterdir() from the pathlib module, which provides a clean object-oriented way to work with file paths. Each Path object in the iteration is checked with .is_file() to skip subdirectories, then .stat().st_size gives the byte size and .suffix returns the file extension including the dot. The result is a list of dictionaries — a flexible format that's easy to convert to JSON or a DataFrame for further analysis.

Common mistakes

  • Forgetting to filter with `.is_file()`, which causes the function to choke on directories.
  • Using `Path(directory).glob('*')` when you don't need hidden files or existing filtering.
  • Assuming files will be returned in sorted order without explicitly sorting.

Variations

  1. Use `os.listdir()` with `os.path.isfile()` if you prefer the older os module.
  2. Convert the dictionary values directly to a pandas DataFrame for tabular analysis.

Real-world use cases

  • Building an inventory report of uploaded files in a storage bucket.
  • Creating a manifest of release artifacts before deploying to production.
  • Preparing a dataset list for a machine learning pipeline by scanning image or CSV files.

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.