Skip to content

Commit ab9a126

Browse files
committed
3.6
1 parent 8b8f323 commit ab9a126

File tree

2 files changed

+47
-17
lines changed

2 files changed

+47
-17
lines changed

Work/fileparse.py

Lines changed: 12 additions & 17 deletions
Original file line numberDiff line numberDiff line change
@@ -1,33 +1,28 @@
11
# fileparse.py
22
#
33
# Exercise 3.3
4-
54
import csv
65

76

8-
def parse_csv(filename, select: list = [], types: list = []):
7+
def parse_csv(
8+
filename: str, select: list = [], types: list = [], has_headers: bool = True
9+
) -> list:
910
"""
1011
Parse a CSV file into a list of records
1112
"""
1213
with open(filename) as f:
1314
rows = csv.reader(f)
14-
15-
# Read the file headers
16-
file_headers = next(rows)
17-
headers = select if select else file_headers
18-
indices = (
19-
[headers.index(name) for name in select]
20-
if select
21-
else [i for i in range(len(headers))]
22-
)
15+
if has_headers:
16+
orig_headers = next(rows)
17+
headers = select if select else orig_headers
18+
indices = [headers.index(name) for name in headers]
2319
records = []
24-
for row in rows:
25-
if not row: # Skip rows with no data
20+
for orig_row in rows:
21+
if not orig_row:
2622
continue
27-
select_row = [row[col] for col in indices]
23+
row = [orig_row[i] for i in indices] if has_headers else orig_row
2824
if types:
29-
select_row = [func(col) for func, col in zip(types, select_row)]
30-
record = dict(zip(headers, select_row))
25+
row = [func(field) for func, field in zip(types, row)]
26+
record = dict(zip(headers, row)) if has_headers else tuple(row)
3127
records.append(record)
32-
3328
return records

Work/fileparse_test.py

Lines changed: 35 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -35,3 +35,38 @@ def test_parse_csv_select_3_5():
3535
{"name": "MSFT", "shares": 50},
3636
{"name": "IBM", "shares": 100},
3737
]
38+
39+
40+
def test_parse_csv_no_headers_3_6():
41+
assert parse_csv("Data/prices.csv", types=[str, float], has_headers=False) == [
42+
("AA", 9.22),
43+
("AXP", 24.85),
44+
("BA", 44.85),
45+
("BAC", 11.27),
46+
("C", 3.72),
47+
("CAT", 35.46),
48+
("CVX", 66.67),
49+
("DD", 28.47),
50+
("DIS", 24.22),
51+
("GE", 13.48),
52+
("GM", 0.75),
53+
("HD", 23.16),
54+
("HPQ", 34.35),
55+
("IBM", 106.28),
56+
("INTC", 15.72),
57+
("JNJ", 55.16),
58+
("JPM", 36.9),
59+
("KFT", 26.11),
60+
("KO", 49.16),
61+
("MCD", 58.99),
62+
("MMM", 57.1),
63+
("MRK", 27.58),
64+
("MSFT", 20.89),
65+
("PFE", 15.19),
66+
("PG", 51.94),
67+
("T", 24.79),
68+
("UTX", 52.61),
69+
("VZ", 29.26),
70+
("WMT", 49.74),
71+
("XOM", 69.35),
72+
]

0 commit comments

Comments
 (0)