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

45 lines
1.3 KiB
Python

#!/usr/bin/env python3
"""Text file analyzer - counts lines, words, characters, bytes.
Usage: python3 file_analyzer.py <filepath>
Outputs JSON to stdout."""
import sys
import json
import os
def analyze_file(filepath):
"""Analyze a text file and return stats."""
if not os.path.exists(filepath):
return {"error": f"File not found: {filepath}"}
if not os.path.isfile(filepath):
return {"error": f"Not a file: {filepath}"}
stats = {
"path": os.path.abspath(filepath),
"size_bytes": os.path.getsize(filepath),
}
try:
with open(filepath, 'r', encoding='utf-8') as f:
content = f.read()
except Exception as e:
return {"error": f"Cannot read file: {e}"}
stats["size_chars"] = len(content)
stats["lines"] = content.count('\n') + (1 if content and not content.endswith('\n') else 0)
stats["words"] = len(content.split())
stats["unique_chars"] = len(set(content))
return stats
if __name__ == "__main__":
if len(sys.argv) != 2:
print(json.dumps({"error": "Usage: file_analyzer.py <filepath>"}))
sys.exit(1)
result = analyze_file(sys.argv[1])
print(json.dumps(result, indent=2))
if "error" in result:
sys.exit(1)