MCPcopy Create free account
hub / github.com/dabeaz-course/practical-python / parse_csv

Function parse_csv

Solutions/8_2/fileparse.py:6–49  ·  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

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

Callers

nothing calls this directly

Calls 1

appendMethod · 0.45

Tested by

no test coverage detected