Re:Advanced Python Mastery – A Course by David Beazley
by mekoka on Wednesday July 19, 2023 @11:46AM
(#36788300)
[ Parent
| on HN ]
Re:Advanced Python Mastery – A Course by David Beazley
by KMnO4 on Wednesday July 19, 2023 @01:04PM
(#36789695)
Swap 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
Re:Advanced Python Mastery – A Course by David Beazley
by tomn on Wednesday July 19, 2023 @04:49PM
(#36793119)
If you do that, it will try to read from a closed file.
Re:Advanced Python Mastery – A Course by David Beazley
by kstrauser on Wednesday July 19, 2023 @05:25PM
(#36793657)
Or 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
]