如何将此代码从Python 2.7转换为Python 3.5以修复---> AttributeError:'_ io.TextIOWrapper'对象没有属性'next'

gou*_*ugh 2 python iterator python-2.7 python-3.x

我使用的是Python 3.5,但本书正在教2.7(打败我为什么在2016年)

使用Python学习Predictive Analytics由Ashish Kumar于2016年2月15日

    >>> data=open(filename,'r')
    >>> cols=data.next().strip().split(',')
    Traceback (most recent call last):
      File "<pyshell#1>", line 1, in <module>
        cols=data.next().strip().split(',')
    AttributeError: '_io.TextIOWrapper' object has no attribute 'next'
    >>> 
Run Code Online (Sandbox Code Playgroud)

我已经读过这个 AttributeError:'_io.TextIOWrapper'对象没有属性'next'python ,我仍然不知道如何让它在Python 3.5 GUI shell中工作.

到目前为止,我理解Python 3.5我必须使用.__next__; 对于Python 2.7 .next.

Mar*_*ers 7

在迭代器上使用该next() 函数:

cols = next(data).strip().split(',')
Run Code Online (Sandbox Code Playgroud)

这与Python版本兼容.

你确实可以互换.next().__next__(),但最好是在这里使用的标准功能,就像你使用len(obj)的不是调用obj.__len__().双下划线方法是Python使用的钩子,您的代码应该使用可能会或可能不会调用这些钩子的标准API.这里尤其如此,其中钩子名称已更改.