forked from dabeaz-course/practical-python
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathpcost_func.py
More file actions
78 lines (61 loc) · 1.44 KB
/
Copy pathpcost_func.py
File metadata and controls
78 lines (61 loc) · 1.44 KB
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
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
# #!/usr/bin/env python
# pcost.py
#
# Exercise 1.27
import sys
import csv
def pcost(filename):
'''
compute total cost
of portfolio
'''
total_cost = 0.0
# try:
# f = open(filename, 'rt')
# except ValueError:
# print("File error")
with open(filename, 'rt') as f:
headers = next(f).split(',')
print(headers)
for line in f:
row = line.split(',')
print(row)
total_cost+=int(row[1])*float(row[2])
# f.close()
##
return total_cost
def pcost_csv(filename):
'''
compute total cost
of portfolio
with using csv module
'''
total_cost = 0.0
# try:
# f = open(filename, 'rt')
# except ValueError:
# print('File error')
with open(filename, 'rt') as f:
rows = csv.reader(f)
headers = next(rows)
#print(headers)
for rno, row in enumerate(rows):
#print(row)
d_item = dict(zip(headers, row))
try:
nshares = int(d_item['shares'])
price = float(d_item['price'])
except:
print('Bad value in row {rno}')
pass
total_cost+=nshares*price
#f.close()
##
return total_cost
if len(sys.argv) == 2:
filename = sys.argv[1]
else:
filename = 'Data/portfoliodate.csv'
#tc = pcost(filename)
tc1 = pcost_csv(filename)
print(tc1)