What's the Pythonic way to go about reading files line by line of the two methods below?
with open('file', 'r') as f:for line in f:print line
or
with open('file', 'r') as f:for line in f.readlines():print line
Or is there something I'm missing?
What's the Pythonic way to go about reading files line by line of the two methods below?
with open('file', 'r') as f:for line in f:print line
or
with open('file', 'r') as f:for line in f.readlines():print line
Or is there something I'm missing?
File handles are their own iterators (specifically, they implement the iterator protocol) so
with open('file', 'r') as f:for line in f:# code
Is the preferred usage. f.readlines()
returns a list of lines, which means absorbing the entire file into memory -> generally ill advised, especially for large files.
It should be pointed out that I agree with the sentiment that context managers are worthwhile, and have included one in my code example.