Re:Advanced Python Mastery – A Course by David Beazley
by me-vs-cat on Wednesday July 19, 2023 @08:21PM
(#36795392)
The parent poster was pointing out that this requires having two in-memory complete copies of the file:
[... for row in open(filename).readlines()]
The readlines return value is one copy, and the list comprehension is another copy. However, that first copy can be avoided with: [... for row in open(filename)]
The entire file must still be read to evaluate the list comprehension.Additionally, this doesn't do what you think it does:
>>> header, *records = (row.strip().split(',') for row in f)
Compare to this, using a variable for clarity: >>> gen = (row.strip().split(',') for row in f)
>>> header, *records = next(gen)
It looks like that code does read the whole file:
(with a foo.csv that is 350955 bytes long:)
I thought that using a list comprehension to bind header and records was eagerly consuming the file, so I changed it to a generator comprehension with nope, I guess the destructuring bind does it? not as neat, though. Is there a golf-ier way to do it?*