Skip to content

Commit 3a1b294

Browse files
committed
exercise 3.10
1 parent 363c00a commit 3a1b294

File tree

1 file changed

+11
-5
lines changed

1 file changed

+11
-5
lines changed

Work/fileparse.py

Lines changed: 11 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -4,24 +4,30 @@
44

55
import csv
66

7-
def parse_csv(filename, select=None, types=None, has_headers=True, delimiter=","):
7+
def parse_csv(filename, select=None, types=None, has_headers=True, delimiter=",", silence_errors=False):
8+
if select and not has_headers:
9+
raise RuntimeError("Select requires column headers")
810
with open(filename) as f:
911
rows = csv.reader(f, delimiter=delimiter)
1012
header = next(rows) if has_headers else []
1113
if select:
1214
indices = [header.index(colname) for colname in select]
1315
header = select
14-
else:
15-
indices = []
1616

1717
records = []
18-
for row in rows:
18+
for row_num, row in enumerate(rows, 1):
1919
if not row:
2020
continue
2121
if select:
2222
row = [row[index] for index in indices]
2323
if types:
24-
row = [func(value) for func, value in zip(types,row)]
24+
try:
25+
row = [func(value) for func, value in zip(types,row)]
26+
except ValueError as e:
27+
if not silence_errors:
28+
print(f"Row {row_num}: Couldn't convert {row}")
29+
print(f"Row {row_num}: Reason {e}")
30+
continue
2531
if header:
2632
record = dict(zip(header, row))
2733
else:

0 commit comments

Comments
 (0)