Hello,
In the following code I do some parsing of files (csv):
Looking forward to your answers :)
In the following code I do some parsing of files (csv):
#!/usr/bin/env python3 import csv def parse_csv(filename, select=None, types=None): ''' Parse a CSV file into a list of records ''' with open(filename) as f: rows = csv.reader(f) # Read the file headers headers = next(rows) if select: indices = [ headers.index(colname) for colname in select ] headers = select else: indices = [] records = [] for row in rows: if not row: # Skip rows with no data continue # Filter the row if specific columns were selected if indices: row = [ row[index] for index in indices ] if types: row = [ func(row) for func, val in zip(types, row) ] record = dict(zip(headers, row)) records.append(record) return records shares_held = parse_csv('../Data/portfoliodate.csv', select=['name', 'time'], types=[str, str]) print(shares_held)My question is related to this sentence:
row = [ func(row) for func, val in zip(types, row) ]Is matching
types
with row
essential here? If I replace it with this:row = [ func(row) for func in types ]the code seems to be behave identically, because you have to match the type and values anyway when calling the function (
types=[str, str]
), otherwise it errors out.Looking forward to your answers :)