|
| 1 | +#!/usr/bin/env python3 |
| 2 | + |
1 | 3 | # report.py
|
2 | 4 | #
|
3 | 5 | # Exercise 2.4
|
4 |
| -import csv |
| 6 | +from fileparse import parse_csv |
5 | 7 |
|
6 | 8 |
|
7 | 9 | def read_portfolio(filename):
|
8 | 10 | '''
|
9 | 11 | Read a stock portfolio file into a list of dictionaries with keys
|
10 | 12 | name, shares, and price.
|
11 | 13 | '''
|
12 |
| - portfolio = [] |
13 |
| - with open(filename, 'rt') as f: |
14 |
| - rows = csv.reader(f) |
15 |
| - headers = next(rows) |
16 |
| - for row in rows: |
17 |
| - record = dict(zip(headers, row)) |
18 |
| - portfolio.append({ |
19 |
| - 'name': record['name'], |
20 |
| - 'shares': int(record['shares']), |
21 |
| - 'price': float(record['price']), |
22 |
| - }) |
23 |
| - return portfolio |
| 14 | + with open(filename) as lines: |
| 15 | + return parse_csv( |
| 16 | + lines, |
| 17 | + select=['name', 'shares', 'price'], |
| 18 | + types=[str, int, float], |
| 19 | + ) |
24 | 20 |
|
25 | 21 |
|
26 | 22 | def read_prices(filename):
|
27 | 23 | '''
|
28 | 24 | Read a CSV file of price data into a dict mapping names to prices.
|
29 | 25 | '''
|
30 |
| - prices = {} |
31 |
| - with open(filename, 'rt') as f: |
32 |
| - rows = csv.reader(f) |
33 |
| - for row in rows: |
34 |
| - if row: |
35 |
| - prices[row[0]] = float(row[1]) |
36 |
| - return prices |
| 26 | + with open(filename) as lines: |
| 27 | + return dict(parse_csv(lines, types=[str, float], has_headers=False)) |
37 | 28 |
|
38 | 29 |
|
39 | 30 | def make_report(portfolio, prices):
|
@@ -68,4 +59,11 @@ def portfolio_report(portfolio_file, prices_file):
|
68 | 59 | print_report(report)
|
69 | 60 |
|
70 | 61 |
|
71 |
| -portfolio_report('Data/portfolio.csv', 'Data/prices.csv') |
| 62 | +def main(args): |
| 63 | + if len(args) != 3: |
| 64 | + raise SystemExit(f'Usage: {args[0]} portfolio_file prices_file') |
| 65 | + portfolio_report(args[1], args[2]) |
| 66 | + |
| 67 | +if __name__ == '__main__': |
| 68 | + import sys |
| 69 | + main(sys.argv) |
0 commit comments