【发布时间】:2020-10-28 09:45:17
【问题描述】:
我正在创建一个文件对象并尝试访问其上的 next()。但是解释器抛出错误,指出该函数不存在。
open("scala.txt").next()
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
AttributeError: '_io.TextIOWrapper' object has no attribute 'next'
但我遇到的许多讨论都提到 next() 可用。但是当我在 for 循环中使用这个对象时,它工作正常。我能否就上述代码抛出错误的原因寻求帮助。
PS:当我创建自己的生成器并尝试调用 next() 时,我遇到了类似的情况。当我将生成器对象放在 for 循环中时,它工作得很好。
>>> x = (e for e in range(1,10))
>>> x.next()
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
AttributeError: 'generator' object has no attribute 'next'
谢谢!
【问题讨论】:
-
请改用
next(foo)。 python 3 中的语法发生了变化。stackoverflow.com/questions/1073396/…
标签: python-3.x