forked from dabeaz-course/practical-python
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathpcost_csv.py
More file actions
29 lines (24 loc) · 722 Bytes
/
pcost_csv.py
File metadata and controls
29 lines (24 loc) · 722 Bytes
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
# pcost_csv.py
import csv
import sys
def portfolio_cost(filename):
with open(filename, 'rt') as f:
rows = csv.reader(f)
headers = next(rows)
total_cost = 0
for rowno, row in enumerate(rows, start=1):
record = dict(zip(headers, row))
try:
nshares = int(record['shares'])
price = float(record['price'])
total_cost += nshares * price
except ValueError:
print(f'Row {rowno}: Bad row: {row}')
return total_cost
if len(sys.argv) == 2:
filename = sys.argv[1]
else:
filename = 'Data/portfolio.csv'
cost = portfolio_cost(filename)
print(filename)
print("Total cost:", cost)