(filename)
| 1 | # pcost.py |
| 2 | |
| 3 | def portfolio_cost(filename): |
| 4 | total_cost = 0.0 |
| 5 | with open(filename) as f: |
| 6 | for line in f: |
| 7 | fields = line.split() |
| 8 | try: |
| 9 | nshares = int(fields[1]) |
| 10 | price = float(fields[2]) |
| 11 | total_cost = total_cost + nshares*price |
| 12 | |
| 13 | # This catches errors in int() and float() conversions above |
| 14 | except ValueError as e: |
| 15 | print("Couldn't parse:", repr(line)) |
| 16 | print("Reason:", e) |
| 17 | |
| 18 | return total_cost |
| 19 | |
| 20 | print(portfolio_cost('../../Data/portfolio3.dat')) |