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.
Python code
32 linesfrom 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
[
{
"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
- Use `os.scandir()` for a lower-level iterator that also yields file types
- 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
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.