Python的"iter"函数示例给出了TypeError

Mar*_*óth 5 python typeerror

python docs中的iter函数示例:

with open("mydata.txt") as fp:
    for line in iter(fp.readline):
        print line
Run Code Online (Sandbox Code Playgroud)

给我这个:

Traceback (most recent call last):
  File "<stdin>", line 2, in <module>
TypeError: 'builtin_function_or_method' object is not iterable
Run Code Online (Sandbox Code Playgroud)

怎么可能?(Python 2.6.4)

Mar*_*óth 4

因为我笨,看不懂:

如果没有第二个参数,o 必须是支持迭代协议(iter () 方法)的集合对象,或者必须支持序列协议(整数参数从 0 开始的getitem () 方法)。如果它不支持这些协议中的任何一个,则会引发 TypeError。

解决方案是提供一个空字符串哨兵。

with open("mydata.txt") as fp:
    for line in iter(fp.readline, ''):
        print line
Run Code Online (Sandbox Code Playgroud)