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.
Python code
26 linesfrom 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
{'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
- Use `os.listdir()` with `os.path.isfile()` if you prefer the older os module.
- 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
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.