Skip to content

Commit 20fff7b

Browse files
authored
Update fileparse.py
1 parent 78ca945 commit 20fff7b

1 file changed

Lines changed: 58 additions & 0 deletions

File tree

‎Work/fileparse.py‎

Lines changed: 58 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1,3 +1,61 @@
11
# fileparse.py
22
#
33
# Exercise 3.3
4+
import csv
5+
6+
def parse_csv(filename, select=None, types=None, has_headers=True, delimiter = ','):
7+
'''
8+
Parse a CSV file into a list of records
9+
'''
10+
with open(filename) as f:
11+
rows = csv.reader(f, delimiter=delimiter)
12+
13+
if has_headers == True:
14+
# Read the file headers
15+
headers = next(rows)
16+
17+
# If a column selector was given, find indices of the specified columns.
18+
# Also narrow the set of headers used for resulting dictionaries
19+
if select:
20+
indices = [headers.index(colname) for colname in select]
21+
headers = select
22+
else:
23+
indices = []
24+
25+
records = []
26+
for row in rows:
27+
if not row: # Skip rows with no data
28+
continue
29+
# Filter the row if specific columns were selected
30+
if indices:
31+
row = [ row[index] for index in indices ]
32+
33+
if types:
34+
row = [func(val) for func, val in zip(types, row) ]
35+
36+
# Make a dictionary
37+
record = dict(zip(headers, row))
38+
records.append(record)
39+
else: # has_headers == False (no headers)
40+
if select:
41+
indices = [headers.index(colname) for colname in select]
42+
else:
43+
indices = []
44+
records = []
45+
for row in rows:
46+
if not row: # Skip rows with no data
47+
continue
48+
# Filter the row if specific columns were selected
49+
if indices:
50+
row = [ row[index] for index in indices ]
51+
52+
if types:
53+
row = [func(val) for func, val in zip(types, row) ]
54+
55+
# Make a dictionary
56+
record = tuple(row)
57+
records.append(record)
58+
59+
return records
60+
61+

0 commit comments

Comments
 (0)