The iter function example at python docs:
with open("mydata.txt") as fp:
for line in iter(fp.readline):
print line
gives me this:
Traceback (most recent call last):
File "<stdin>", line 2, in <module>
TypeError: 'builtin_function_or_method' object is not iterable
How's that possible? (Python 2.6.4)
It's because I'm stupid and can't read:
Without a second argument, o must be a collection object which supports the iteration protocol (the iter() method), or it must support the sequence protocol (the getitem() method with integer arguments starting at 0). If it does not support either of those protocols, TypeError is raised.
Solution is to provide an empty string sentinel.
with open("mydata.txt") as fp:
for line in iter(fp.readline, ''):
print line
Python file
objects are iterable, hence there is no need to explicitly call iter()
. To read a file line by line you can simply write:
with open("mydata.txt") as fp:
for line in fp:
print line
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With