Thanks to visit codestin.com
Credit goes to github.com

Skip to content

Commit 5835b01

Browse files
committed
Chapter 3 done.
1 parent 5c782f4 commit 5835b01

File tree

3 files changed

+56
-66
lines changed

3 files changed

+56
-66
lines changed

Work/fileparse.py

Lines changed: 23 additions & 24 deletions
Original file line numberDiff line numberDiff line change
@@ -6,7 +6,7 @@
66

77

88
def parse_csv(
9-
filename,
9+
lines,
1010
select=None,
1111
types=None,
1212
has_headers=True,
@@ -19,29 +19,28 @@ def parse_csv(
1919
if select and not has_headers:
2020
raise RuntimeError("Select argument requires column headers")
2121

22-
with open(filename) as f:
23-
rows = csv.reader(f, delimiter=delimiter)
24-
headers = next(rows) if has_headers else []
22+
rows = csv.reader(lines, delimiter=delimiter)
23+
headers = next(rows) if has_headers else []
24+
if select:
25+
indices = [headers.index(colname) for colname in select]
26+
headers = select
27+
records = []
28+
for idx, row in enumerate(rows, start=1):
29+
if not row:
30+
continue
2531
if select:
26-
indices = [headers.index(colname) for colname in select]
27-
headers = select
28-
records = []
29-
for idx, row in enumerate(rows, start=1):
30-
if not row:
32+
row = [row[index] for index in indices]
33+
if types:
34+
try:
35+
row = [func(val) for func, val in zip(types, row)]
36+
except ValueError as e:
37+
if not silence_errors:
38+
print(f'Row {idx}: Couldn\'t convert {row}')
39+
print(f'Row {idx}: Reason {e}')
3140
continue
32-
if select:
33-
row = [row[index] for index in indices]
34-
if types:
35-
try:
36-
row = [func(val) for func, val in zip(types, row)]
37-
except ValueError as e:
38-
if not silence_errors:
39-
print(f'Row {idx}: Couldn\'t convert {row}')
40-
print(f'Row {idx}: Reason {e}')
41-
continue
42-
if headers:
43-
record = dict(zip(headers, row))
44-
else:
45-
record = tuple(row)
46-
records.append(record)
41+
if headers:
42+
record = dict(zip(headers, row))
43+
else:
44+
record = tuple(row)
45+
records.append(record)
4746
return records

Work/pcost.py

100644100755
Lines changed: 14 additions & 21 deletions
Original file line numberDiff line numberDiff line change
@@ -1,31 +1,24 @@
1+
#!/usr/bin/env python3
2+
13
# pcost.py
24
#
35
# Exercise 1.27
4-
import sys
5-
import csv
6+
from report import read_portfolio
67

78

89
def portfolio_cost(filename):
910
'''Return portfolio cost.'''
10-
total_cost = 0.0
11-
with open(filename, 'rt') as file:
12-
rows = csv.reader(file)
13-
headers = next(rows)
14-
for rowno, row in enumerate(rows, start=1):
15-
record = dict(zip(headers, row))
16-
try:
17-
nshares = int(record['shares'])
18-
price = float(record['price'])
19-
total_cost += nshares * price
20-
except ValueError:
21-
print(f'Row {rowno}: Bad row: {row}')
22-
return total_cost
11+
portfolio = read_portfolio(filename)
12+
return sum([s['shares'] * s['price'] for s in portfolio])
13+
2314

15+
def main(args):
16+
if len(args) != 2:
17+
raise SystemExit(f'Usage: {args[0]} portfolio_file')
18+
cost = portfolio_cost(args[1])
19+
print(f'Total cost: {cost}')
2420

25-
if len(sys.argv) == 2:
26-
filename = sys.argv[1]
27-
else:
28-
filename = '../Work/Data/portfolio.csv'
2921

30-
cost = portfolio_cost(filename)
31-
print(f'Total cost: {cost}')
22+
if __name__ == '__main__':
23+
import sys
24+
main(sys.argv)

Work/report.py

100644100755
Lines changed: 19 additions & 21 deletions
Original file line numberDiff line numberDiff line change
@@ -1,39 +1,30 @@
1+
#!/usr/bin/env python3
2+
13
# report.py
24
#
35
# Exercise 2.4
4-
import csv
6+
from fileparse import parse_csv
57

68

79
def read_portfolio(filename):
810
'''
911
Read a stock portfolio file into a list of dictionaries with keys
1012
name, shares, and price.
1113
'''
12-
portfolio = []
13-
with open(filename, 'rt') as f:
14-
rows = csv.reader(f)
15-
headers = next(rows)
16-
for row in rows:
17-
record = dict(zip(headers, row))
18-
portfolio.append({
19-
'name': record['name'],
20-
'shares': int(record['shares']),
21-
'price': float(record['price']),
22-
})
23-
return portfolio
14+
with open(filename) as lines:
15+
return parse_csv(
16+
lines,
17+
select=['name', 'shares', 'price'],
18+
types=[str, int, float],
19+
)
2420

2521

2622
def read_prices(filename):
2723
'''
2824
Read a CSV file of price data into a dict mapping names to prices.
2925
'''
30-
prices = {}
31-
with open(filename, 'rt') as f:
32-
rows = csv.reader(f)
33-
for row in rows:
34-
if row:
35-
prices[row[0]] = float(row[1])
36-
return prices
26+
with open(filename) as lines:
27+
return dict(parse_csv(lines, types=[str, float], has_headers=False))
3728

3829

3930
def make_report(portfolio, prices):
@@ -68,4 +59,11 @@ def portfolio_report(portfolio_file, prices_file):
6859
print_report(report)
6960

7061

71-
portfolio_report('Data/portfolio.csv', 'Data/prices.csv')
62+
def main(args):
63+
if len(args) != 3:
64+
raise SystemExit(f'Usage: {args[0]} portfolio_file prices_file')
65+
portfolio_report(args[1], args[2])
66+
67+
if __name__ == '__main__':
68+
import sys
69+
main(sys.argv)

0 commit comments

Comments
 (0)