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