How to List File Metadata in Python

This code walks a directory and returns a list of JSON-ready dicts with each file's name, size, and modification time.

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

Python code

32 lines
Python 3.9+
from pathlib import Path
import json

def format_files_data(directory_path):
    """Return a list of JSON-serializable dicts with file metadata."""
    base = Path(directory_path)
    if not base.is_dir():
        raise ValueError(f"Not a directory: {directory_path}")

    files_data = []
    for file_path in base.iterdir():
        if file_path.is_file():
            stats = file_path.stat()
            files_data.append({
                "name": file_path.name,
                "size_bytes": stats.st_size,
                "modified_time": stats.st_mtime,
            })

    return files_data

if __name__ == "__main__":
    import tempfile
    from pathlib import Path

    with tempfile.TemporaryDirectory() as tmpdir:
        tmp = Path(tmpdir)
        (tmp / "notes.txt").write_text("hello world")
        (tmp / "data.csv").write_text("a,b,c\n1,2,3")

        result = format_files_data(tmpdir)
        print(json.dumps(result, indent=2))

Output

stdout
[
  {
    "name": "notes.txt",
    "size_bytes": 11,
    "modified_time": 1734567890.0
  },
  {
    "name": "data.csv",
    "size_bytes": 10,
    "modified_time": 1734567891.0
  }
]

How it works

The function takes a directory path, verifies it exists with Path.is_dir(), then iterates over entries using Path.iterdir(). For each regular file, it calls stat() to get metadata like size and modification time. The returned list of dicts can be serialized directly with json.dumps for APIs or config files. Using pathlib makes the code cross-platform and more readable than bare os calls.

Common mistakes

  • Forgetting to check if the path is a directory before calling `iterdir()`
  • Including subdirectories in the result by not filtering with `is_file()`
  • Relying on `os.listdir()` which returns strings instead of `Path` objects

Variations

  1. Use `os.scandir()` for a lower-level iterator that also yields file types
  2. Return file names sorted with `sorted(base.iterdir(), key=lambda p: p.name)`

Real-world use cases

  • Building a file explorer API endpoint that lists files in a user's upload folder.
  • Creating a backup script that logs file sizes and modification times before archiving.
  • Generating a manifest for a data pipeline that tracks processed files by metadata.

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.