3 ms·
Whenever you see this pattern, think of using a generator instead: def read_portfolio(filename): with open(filename) as f: rows = csv.r
by nicwolff 3y ago
Whenever you see this pattern, think of using a generator instead:
def read_portfolio(filename):
with open(filename) as f:
rows = csv.reader(f)
headers = next(rows)
for row in rows:
yield {
'name' : row[0],
'shares' : int(row[1]),
'price' : float(row[2]),
}
Now you can call read_portfolio() to get an iterable that lazily reads the file and yields dicts:
portfolio = read_portfolio()
for record in portfolio:
print '{shares} shares of {name} at ${price}'.format_map(record)
- drexlspivey 3y agoor use the built-in csv.DictReader :)