Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Python's example for "iter" function gives me TypeError

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)

like image 367
Martin Tóth Avatar asked Oct 13 '22 21:10

Martin Tóth


2 Answers

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
like image 117
Martin Tóth Avatar answered Nov 15 '22 09:11

Martin Tóth


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
like image 36
Tendayi Mawushe Avatar answered Nov 15 '22 08:11

Tendayi Mawushe