4 ms·
def read_portfolio(filename): record = lambda r: { 'name': r[0], 'shares': int(r[1]), 'price': float(r[2]),
by mekoka 3y ago
def read_portfolio(filename):
record = lambda r: {
'name': r[0],
'shares': int(r[1]),
'price': float(r[2]),
}
with open(filename) as f:
rows = csv.reader(f)
headers = next(rows)
return [record(r) for r in rows]
- KMnO4 3y agoSwap the square brackets for parentheses in the return statement and it will return a generator expression. That will read the file as needed (ie as you iterate over it) instead of loading the entire thing in memory. for record in read_portfolio(fn): # do stuff
- tomn 3y agoIf you do that, it will try to read from a closed file.
- kstrauser 3y agoOr even: def read_portfolio(filename): with open(filename) as f: rows = csv.reader(f) headers = next(rows) return [ { "name": r[0], "shares": int(r[1]), "price": float(r[2]), } for r in rows ]