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? (Pyt开发者_运维技巧hon 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
The only thing I can think about is that you don't have a file called mydata.txt or it is in the wrong place.
精彩评论