Files
troupe-standup/wizard-work/spark/py_line_counter.py
T

38 lines
1.2 KiB
Python

#!/usr/bin/env python3
"""Count lines in Python files."""
import os
import sys
from pathlib import Path
def count_python_files(directory: str) -> dict:
"""Count Python files and their lines in a directory."""
result = {"files": 0, "total_lines": 0, "by_file": []}
for root, dirs, files in os.walk(directory):
for f in files:
if f.endswith('.py'):
filepath = os.path.join(root, f)
result["files"] += 1
try:
with open(filepath, 'r') as fp:
lines = len(fp.readlines())
result["total_lines"] += lines
result["by_file"].append({"path": filepath, "lines": lines})
except Exception as e:
result["by_file"].append({"path": filepath, "error": str(e)})
return result
if __name__ == "__main__":
if len(sys.argv) < 2:
target = "."
else:
target = sys.argv[1]
result = count_python_files(target)
print(f"Found {result['files']} Python files with {result['total_lines']} total lines")
print(f"FILE_COUNT={result['files']}")
print(f"TOTAL_LINES={result['total_lines']}")