679 B
679 B
Exercise 1.6 - Solution
(b) Main Module
# pcost.py
def portfolio_cost(filename):
= 0.0
total_cost with open(filename) as f:
for line in f:
= line.split()
fields try:
= int(fields[1])
nshares = float(fields[2])
price = total_cost + nshares * price
total_cost
# This catches errors in int() and float() conversions above
except ValueError as e:
print("Couldn't parse:", line)
print("Reason:", e)
return total_cost
if __name__ == '__main__':
print(portfolio_cost('Data/portfolio.dat'))