MCPcopy Index your code
hub / github.com/dabeaz-course/practical-python / parse_csv

Function parse_csv

Solutions/5_8/fileparse.py:4–47  ·  view source on GitHub ↗

Parse a CSV file into a list of records with type conversion.

(lines, select=None, types=None, has_headers=True, delimiter=',', silence_errors=False)

Source from the content-addressed store, hash-verified

2import csv
3
4def parse_csv(lines, select=None, types=None, has_headers=True, delimiter=',', silence_errors=False):
5 '''
6 Parse a CSV file into a list of records with type conversion.
7 '''
8 if select and not has_headers:
9 raise RuntimeError('select requires column headers')
10
11 rows = csv.reader(lines, delimiter=delimiter)
12
13 # Read the file headers (if any)
14 headers = next(rows) if has_headers else []
15
16 # If specific columns have been selected, make indices for filtering and set output columns
17 if select:
18 indices = [ headers.index(colname) for colname in select ]
19 headers = select
20
21 records = []
22 for rowno, row in enumerate(rows, 1):
23 if not row: # Skip rows with no data
24 continue
25
26 # If specific column indices are selected, pick them out
27 if select:
28 row = [ row[index] for index in indices]
29
30 # Apply type conversion to the row
31 if types:
32 try:
33 row = [func(val) for func, val in zip(types, row)]
34 except ValueError as e:
35 if not silence_errors:
36 print(f"Row {rowno}: Couldn't convert {row}")
37 print(f"Row {rowno}: Reason {e}")
38 continue
39
40 # Make a dictionary or a tuple
41 if headers:
42 record = dict(zip(headers, row))
43 else:
44 record = tuple(row)
45 records.append(record)
46
47 return records

Callers

nothing calls this directly

Calls 1

appendMethod · 0.45

Tested by

no test coverage detected