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.
Python code
27 linesfrom 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
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
- Use `os.scandir()` with `entry.is_file()` for a lower-level alternative
- 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
More from Files & data
- Append a Line to a Log File in Python easy
- Audit File Permissions Across a Project in Python easy
- Automatically Detect Corrupted Files Using SHA-256 Checksums in Python easy
- Automatically Highlight Data Validation Errors Inside Excel Files in Python easy
- Build a Command-Line To-Do List Application with Data Persistence in Python easy
- Build a File Index by Relative Path Hash Map in Python easy
Keep learning
Related tutorials and quizzes for this topic.