summarize.py 1.4 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243
  1. #!/usr/bin/env python3
  2. import csv
  3. import sys
  4. from collections import OrderedDict
  5. from decimal import Decimal
  6. INPUT_HEADER = ["日期", "姓名", "类别", "金额"]
  7. SUMMARY_HEADER = ["姓名", "报销总额"]
  8. def main():
  9. if len(sys.argv) != 4:
  10. raise SystemExit("usage: summarize.py INPUT_CSV SUMMARY_CSV OVER_500_CSV")
  11. input_path, summary_path, filtered_path = sys.argv[1:]
  12. with open(input_path, encoding="utf-8-sig", newline="") as source:
  13. reader = csv.DictReader(source)
  14. if reader.fieldnames != INPUT_HEADER:
  15. raise ValueError("unexpected input columns")
  16. rows = list(reader)
  17. totals = OrderedDict()
  18. for row in rows:
  19. name = row["姓名"]
  20. totals[name] = totals.get(name, Decimal("0")) + Decimal(row["金额"])
  21. with open(summary_path, "w", encoding="utf-8", newline="") as output:
  22. writer = csv.writer(output)
  23. writer.writerow(SUMMARY_HEADER)
  24. for name, total in totals.items():
  25. writer.writerow([name, f"{total:.2f}"])
  26. with open(filtered_path, "w", encoding="utf-8", newline="") as output:
  27. writer = csv.writer(output)
  28. writer.writerow(INPUT_HEADER)
  29. for row in rows:
  30. if Decimal(row["金额"]) > Decimal("500"):
  31. writer.writerow([row[column] for column in INPUT_HEADER])
  32. if __name__ == "__main__":
  33. main()