Python的“iter”函数示例给出了TypeError

前端之家收集整理的这篇文章主要介绍了Python的“iter”函数示例给出了TypeError前端之家小编觉得挺不错的,现在分享给大家,也给大家做个参考。

python docs的iter函数示例:

with open("mydata.txt") as fp:
    for line in iter(fp.readline):
        print line

给我这个:

Traceback (most recent call last):
  File "

怎么可能? (Python 2.6.4)

最佳答案
这是因为我很蠢,读不懂:

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.

解决方案是提供一个空字符串sentinel.

with open("mydata.txt") as fp:
    for line in iter(fp.readline,''):
        print line

猜你在找的Python相关文章