Repository navigation
Expand file tree
/
Copy pathfileparse.py
More file actions
56 lines (46 loc) · 1.62 KB
/
Copy pathfileparse.py
File metadata and controls
56 lines (46 loc) · 1.62 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
# fileparse.py
#
# Exercise 3.3
import csv
def parse_csv(file_lines, select=None, types=None, has_headers=True, delimiter=',', silence_errors=False):
""" Parse a CSV file into a list of records
"""
if select and not has_headers:
raise RuntimeError('select argument requires column headers')
lines = csv.reader(file_lines, delimiter=delimiter)
#Read the file headers
if has_headers:
headers = next(lines)
# 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 = []
rownum = 0
for line in lines:
rownum += 1
if not line: #skip lines with no data
continue
try:
# filter the line if specific columns were selected
if indices:
line = [ line[index] for index in indices]
# perform type conversion
if types:
line = [func(val) for func, val in zip(types, line)]
if has_headers:
# make a dictionary
record = dict(zip(headers, line))
else:
# make a tuple
record = tuple(line)
records.append(record)
except ValueError as e:
if not silence_errors:
print(f'line {rownum}: couldn\'t convert {line}')
print(f'line {rownum}: reason {e}')
continue
return records