如何将此代码从Python 2.7转换为Python 3.5以修复---> AttributeError:'_ io.TextIOWrapper'对象没有属性'next' [英] How to translate this code from Python 2.7 to Python 3.5 to fix --- > AttributeError: '_io.TextIOWrapper' object has no attribute 'next'

查看:296
本文介绍了如何将此代码从Python 2.7转换为Python 3.5以修复---> AttributeError:'_ io.TextIOWrapper'对象没有属性'next'的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

I am using Python 3.5 but this book is teaching 2.7 (beats me why in 2016)

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

Learning Predictive Analytics with Python by Ashish Kumar Feb 15, 2016

    >>> 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'
    >>> 

我已经读过这个
AttributeError:'_ io.TextIOWrapper'对象没有属性'next'python
我仍​​然不喜欢我不知道如何让它在Python 3.5 GUI shell中运行。

I have read this AttributeError: '_io.TextIOWrapper' object has no attribute 'next' python and I still don't know how to get it to work in Python 3.5 GUI shell.

到目前为止,我理解Python 3.5我必须使用 .__ next__ ; for Python 2.7 .next

So far, I understand for Python 3.5 I have to use .__next__; for Python 2.7 .next.

推荐答案

使用 next() function on on iterators:

Use the next() function on iterators:

cols = next(data).strip().split(',')

这与Python版本兼容。

This is compatible across Python versions.

您确实可以将 .next()换成 .__ next __(),但最好在这里使用标准函数就像你使用 len(obj)而不是调用 obj .__ len __()一样。双下划线方法是Python使用的 hook ,您的代码应使用可能会或可能不会调用这些挂钩的标准API。这里尤其如此,钩子名称已更改。

You could indeed swap .next() for .__next__(), but it is better to use the standard function here, just as you'd use len(obj) instead of calling obj.__len__(). Double-underscore methods are hooks used by Python, your code should use the standard APIs that may or may not call those hooks. This is especially true here, where the hook name changed.

这篇关于如何将此代码从Python 2.7转换为Python 3.5以修复---&gt; AttributeError:'_ io.TextIOWrapper'对象没有属性'next'的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆