Question

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)

Was it helpful?

Solution

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

OTHER TIPS

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.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top