report.py
1# report.py — ledger.csv in, report.txt out
2from pathlib import Path
3
4def load(path):
5 rows = []
6 with open(path, encoding="utf-8") as f:
7 header = f.readline()
8 for line in f:
9 parts = line.strip().split(",")
10 ticker, name, shares, price = parts
11 try:
12 rows.append((name, int(shares), float(price)))
13 except ValueError:name the error you expect
14 print(f"skipped {ticker}: bad number")
15 return rows
16
17def write_report(rows, path):
18 total = 0.0
19 with open(path, erases first"w", encoding="utf-8") as out:
20 for name, shares, price in rows:
21 out.write(f"{name:<9}{shares * price:>10,.2f}\n")
22 total += shares * price
23 out.write(f"{'total':<9}{total:>10,.2f}\n")
24 return total
25
26rows = load(Path("ledger.csv"))
27total = write_report(rows, Path("report.txt"))
28assert total > 0, "an empty report?"
29print(len(rows), "positions, total", round(total, 2))
30print(Path("report.txt").read_text())