Skip to content

Commit adaefca

Browse files
committed
3.4
1 parent 1736c36 commit adaefca

File tree

2 files changed

+35
-0
lines changed

2 files changed

+35
-0
lines changed

Work/fileparse.py

Lines changed: 27 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1,3 +1,30 @@
11
# fileparse.py
22
#
33
# Exercise 3.3
4+
5+
import csv
6+
7+
def parse_csv(filename, select: list):
8+
'''
9+
Parse a CSV file into a list of records
10+
'''
11+
with open(filename) as f:
12+
rows = csv.reader(f)
13+
14+
# Read the file headers
15+
headers = next(rows)
16+
select_indices = [headers.index(name) for name in select] \
17+
if select \
18+
else [i for i in range(len(headers))]
19+
if select:
20+
headers = select
21+
records = []
22+
for row in rows:
23+
if not row: # Skip rows with no data
24+
continue
25+
record = dict(zip(
26+
headers,
27+
[row[i] for i in select_indices]))
28+
records.append(record)
29+
30+
return records

Work/fileparse_test.py

Lines changed: 8 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,8 @@
1+
from fileparse import parse_csv
2+
3+
def test_parse_csv_select_3_4():
4+
assert parse_csv('Data/portfolio.csv', select=['name','shares']) == \
5+
[{'name': 'AA', 'shares': '100'}, {'name': 'IBM', 'shares': '50'},
6+
{'name': 'CAT', 'shares': '150'}, {'name': 'MSFT', 'shares': '200'},
7+
{'name': 'GE', 'shares': '95'}, {'name': 'MSFT', 'shares': '50'},
8+
{'name': 'IBM', 'shares': '100'}]

0 commit comments

Comments
 (0)