Visitar URL original
complete section 3.2 · dabeaz-course/practical-python@7f6e3a5 · GitHub
Skip to content

Commit 7f6e3a5

Browse files
author
iram lee
committed
complete section 3.2
1 parent c068983 commit 7f6e3a5

1 file changed

Lines changed: 42 additions & 0 deletions

File tree

‎Work/fileparse.py‎

Lines changed: 42 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1,3 +1,45 @@
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+
""" Parse a CSV file into a list of records
8+
"""
9+
with open(filename) as f:
10+
rows = csv.reader(f, delimiter=delimiter)
11+
12+
#Read the file headers
13+
if has_headers:
14+
headers = next(rows)
15+
16+
# If a column selector was given, find indices of the specified columns.
17+
# Also narrow the set of headers used for resulting dictionaries
18+
if select:
19+
indices = [headers.index(colname) for colname in select]
20+
headers = select
21+
else:
22+
indices = []
23+
24+
records = []
25+
for row in rows:
26+
if not row: #Skip rows with no data
27+
continue
28+
29+
# Filter the row if specific columns were selected
30+
if indices:
31+
row = [ row[index] for index in indices]
32+
# Perform type conversion
33+
if types:
34+
row = [func(val) for func, val in zip(types, row)]
35+
36+
if has_headers:
37+
# Make a dictionary
38+
record = dict(zip(headers, row))
39+
else:
40+
# Make a tuple
41+
record = tuple(row)
42+
43+
records.append(record)
44+
45+
return records

0 commit comments

Comments
 (0)