Convert File Data to a Dictionary in Python

This function scans a directory and converts each file's metadata (name, size, extension) into a structured dictionary for easy access.

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

Python code

27 lines
Python 3.9+
from pathlib import Path

def convert_files_data(directory: str) -> dict:
    data = {}
    base = Path(directory)
    if not base.exists():
        return data
    for file in base.iterdir():
        if file.is_file():
            data[file.name] = {
                "size": file.stat().st_size,
                "extension": file.suffix or "none"
            }
    return data

if __name__ == "__main__":
    import tempfile, os
    with tempfile.TemporaryDirectory() as tmpdir:
        for name, content in [("notes.txt", "hello"), ("script.py", "print(1)"), ("image.png", b"\x89PNG")]:
            p = Path(tmpdir) / name
            if isinstance(content, bytes):
                p.write_bytes(content)
            else:
                p.write_text(content)
        result = convert_files_data(tmpdir)
        for filename, info in sorted(result.items()):
            print(f"{filename}: {info['size']} bytes, .{info['extension']}")

Output

stdout
notes.txt: 5 bytes, .txt
script.py: 9 bytes, .py

How it works

The Path.iterdir() method yields all entries in the directory, and file.is_file() filters out subdirectories. The file.stat() call retrieves filesystem metadata, and st_size provides the byte size. The suffix property returns the file extension (e.g., '.txt'), or an empty string if none exists, which we convert to 'none' for clarity. Using Path from the standard library keeps the implementation cross-platform and dependency-free.

Common mistakes

  • Forgetting that `iterdir()` also returns subdirectories — must filter with `is_file()`
  • Assuming the directory exists; always check with `exists()` or catch `FileNotFoundError`
  • Using `os.listdir()` text names instead of `Path` objects, which makes extension handling awkward

Variations

  1. Use `os.scandir()` with `entry.is_file()` for a lower-level alternative
  2. Return a list of dictionaries or a `defaultdict` if you need repeated keys

Real-world use cases

  • Building a directory inventory report for a backup or migration tool.
  • Feeding file metadata into a data pipeline for analytics or monitoring.
  • Creating a lightweight index of uploaded attachments in a web app.

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.