문제

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

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.

라이센스 : CC-BY-SA ~와 함께 속성
제휴하지 않습니다 StackOverflow
scroll top