33# Exercise 3.3
44import csv
55
6- def parse_csv (filename , select = None , types = None , has_headers = True , delimiter = ',' , silence_errors = True ):
6+ def parse_csv (file_obj , select = None , types = None , has_headers = True , delimiter = ',' , silence_errors = True ):
77 '''
88 Parse a CSV file into a list of records
99 '''
10- with open (filename ) as f :
11- rows = csv .reader (f , delimiter = delimiter )
10+ rows = csv .reader (file_obj , delimiter = delimiter )
1211
13- if select and not has_headers :
14- raise RuntimeError ('select argument requires column headers' )
12+ if select and not has_headers :
13+ raise RuntimeError ('select argument requires column headers' )
1514
16- #Read headers
15+ #Read headers
16+ if has_headers :
17+ headers = next (rows )
18+
19+ if select :
20+ indeces = [headers .index (colname ) for colname in select ]
1721 if has_headers :
18- headers = next (rows )
19-
20- if select :
21- indeces = [headers .index (colname ) for colname in select ]
22- if has_headers :
23- headers = select
24- else :
25- indeces = []
22+ headers = select
23+ else :
24+ indeces = []
2625
27- records = []
28- for rowNum , row in enumerate (rows , start = 1 ):
29- if not row : #skip empty rows
30- continue
31-
32- try :
33- if indeces :
34- row = [row [index ] for index in indeces ]
35- if types :
36- row = [func (val ) for func , val in zip (types , row )]
26+ records = []
27+ for rowNum , row in enumerate (rows , start = 1 ):
28+ if not row : #skip empty rows
29+ continue
30+
31+ try :
32+ if indeces :
33+ row = [row [index ] for index in indeces ]
34+ if types :
35+ row = [func (val ) for func , val in zip (types , row )]
3736
38- if has_headers :
39- records .append ({name : value for name , value in zip (headers ,row )})
40- else :
41- records .append (row )
42- except ValueError as ve :
43- if not silence_errors :
44- print (f'Row { rowNum } : Couldn\' t convert { row } ' )
45- print (f'Row { rowNum } : Reason { ve } ' )
37+ if has_headers :
38+ records .append ({name : value for name , value in zip (headers ,row )})
39+ else :
40+ records .append (row )
41+ except ValueError as ve :
42+ if not silence_errors :
43+ print (f'Row { rowNum } : Couldn\' t convert { row } ' )
44+ print (f'Row { rowNum } : Reason { ve } ' )
4645 return records
0 commit comments