File tree Expand file tree Collapse file tree
Expand file tree Collapse file tree Original file line number Diff line number Diff line change 22#
33# Exercise 1.27
44import sys
5+ import csv
56
67def portfolio_cost (filename ):
7- cost = 0.0
8+ total_cost = 0.0
89 stock_price = 0.0
910 num_of_shares = 0
1011 f = open (filename , 'rt' )
11- headers = next (f )
12+ lines = csv .reader (f )
13+ headers = next (lines )
1214
13- for line in f :
15+ for lineno , line in enumerate (lines , start = 1 ):
16+ record = dict (zip (headers , line ))
1417 try :
15- stock = line . split ( ',' )
16- num_of_shares = int ( stock [ 1 ])
17- stock_price = float ( stock [ 2 ]. strip ())
18- cost += ( num_of_shares * stock_price )
18+ nshares = int ( record [ 'shares' ] )
19+ price = float ( record [ 'price' ])
20+ total_cost += nshares * price
21+ # This catches errors in int() and float() conversions above
1922 except ValueError :
20- print (' Bad line' , line )
23+ print (f'Row { lineno } : Bad row: { line } ' )
2124
2225 f .close ()
23- return cost
26+ return total_cost
2427
2528
2629if len (sys .argv ) == 2 :
2730 filename = sys .argv [1 ]
2831else :
29- filename = 'Data/portfolio .csv'
32+ filename = 'Data/portfoliodate .csv'
3033
3134cost = portfolio_cost (filename )
3235print ('Total cost:' , cost )
Original file line number Diff line number Diff line change @@ -10,7 +10,8 @@ def read_portfolio(filename):
1010 rows = csv .reader (f )
1111 headers = next (rows )
1212 for row in rows :
13- holding = {'name' : row [0 ], 'shares' : int (row [1 ]), 'price' : float (row [2 ])}
13+ record = dict (zip (headers , row ))
14+ holding = record
1415 portfolio .append (holding )
1516 return portfolio
1617
@@ -34,9 +35,9 @@ def make_report(portfolio, prices):
3435
3536 for holding in portfolio :
3637 name = holding ['name' ]
37- shares = holding ['shares' ]
38+ shares = int ( holding ['shares' ])
3839 price = prices [name ]
39- change = price - holding ['price' ]
40+ change = price - float ( holding ['price' ])
4041 updated_portfolio .append ((name , shares , price , change ))
4142
4243 return updated_portfolio
@@ -54,7 +55,7 @@ def print_report(report):
5455 print (f'{ name :>10s} { shares :>10d} { money :>10s} { change :>10.2f} ' )
5556
5657
57- portfolio = read_portfolio ('Data/portfolio .csv' )
58+ portfolio = read_portfolio ('Data/portfoliodate .csv' )
5859prices = read_prices ('Data/prices.csv' )
5960report = make_report (portfolio , prices )
6061print_report (report )
You can’t perform that action at this time.
0 commit comments