forked from dabeaz-course/practical-python
-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathfileparse.py
More file actions
67 lines (51 loc) · 1.7 KB
/
fileparse.py
File metadata and controls
67 lines (51 loc) · 1.7 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
# fileparse.py
#
# Exercise 3.3
import csv
from pprint import pprint
def parse_csv(lines, select=None, types=None, has_headers=True, silence_errors=True, delimiter=','):
"""
Parse a CSV file into a list of records
"""
if not has_headers and select:
raise RuntimeError("wrong combination of args")
rows = csv.reader(lines, delimiter=delimiter)
# Read the file headers
if has_headers:
headers = next(rows)
else:
headers = None
# If a column selector was given, find indices of the specified columns.
# Also narrow the set of headers used for resulting dictionaries
if select:
indices = [headers.index(colname) for colname in select]
headers = select
else:
indices = []
records = []
for index, row in enumerate(rows):
try:
if not row: # Skip rows with no data
continue
# Filter the row if specific columns were selected
if indices:
row = [row[index] for index in indices]
if types:
row = [func(val) for func, val in zip(types, row)]
if headers:
record = dict(zip(headers, row))
else:
record = tuple(row)
records.append(record)
except ValueError as e:
if not silence_errors:
print(f"Row {index + 1}: Couldn't convert", row)
print(f"Row {index + 1}: Reason", e)
pass
return records
def main():
with open('Data/portfolio.csv', 'rt') as f:
portfolio = parse_csv(f, types=[str, int, float], silence_errors=False)
pprint(portfolio)
if __name__ == '__main__':
main()