Re:Don’t Slurp: How to Read Files in Python
by cpjk on Friday September 27, 2013 @05:50PM
(#6459803)
Forgive me, but doesn't file.readline() provide the same functionality for reading a single line at a time from a file?
[ Parent
| on HN ]
Re:Don’t Slurp: How to Read Files in Python
by chaosphere2112 on Friday September 27, 2013 @06:20PM
(#6459939)
Yeah, but aren't we actually supposed to do this?
for line in file:
Re:Don’t Slurp: How to Read Files in Python
by scott_s on Friday September 27, 2013 @06:48PM
(#6460036)
Yes, and that is the idiomatic way to read files in Python. I guess me and the author are looking at different Python programs, because slurping the whole file is not "by far the most common way" I have seen files read in the wild.
Re:Don’t Slurp: How to Read Files in Python
by rprospero on Friday September 27, 2013 @07:08PM
(#6460109)
Most of my code slurps the entire file at a time. I can't actually think of any code we have that streams the code.
Then again, most of my files are three dimensional matrices. There's nothing I can really do on a line by line basis.
Yes, this is essentially looping over successive calls to file.readline()
Re:Don’t Slurp: How to Read Files in Python
by tjgq on Friday September 27, 2013 @08:11PM
(#6460325)
With at least one small (and usually irrelevant) difference: "for line in file" has its own internal buffering which cannot be turned off with python -u.
I learned this the hard way when debugging a Python script that read from tail -f output...
Re:Don’t Slurp: How to Read Files in Python
by gcr on Saturday September 28, 2013 @06:59PM
(#6463428)
I thought a function that reads a line from a file would read the entire line and block until doing so. How would turning off line buffering change that? Do you expect 'for line in file' to yield as many bytes as is available if a full line can't be read yet?