【问题标题】:AttributeError: '_io.TextIOWrapper' object has no attribute 'next' [duplicate]AttributeError:'_io.TextIOWrapper'对象没有属性'next'[重复]
【发布时间】:2017-03-28 21:40:58
【问题描述】:

使用我在 Python 2 中编写的函数,我试图连接 csv 文件:

def concat_csv():
    """
    A function to concatenate the previously wrangled csv files in current working dir
    """
    with open('2017_oldnew.csv', 'a') as f_out:
        # First file
        with open('old.csv') as f_read:
            for line in f_read:
                f_out.write(line)
        # Second file
        with open('new.csv') as f_read:
            f_read.next()
            for line in f_read:
                f_out.write(line)

但是,运行这个 Python 3 会给我一条错误消息:

---------------------------------------------------------------------------
AttributeError                            Traceback (most recent call last)
<ipython-input-110-a5a430e1b905> in <module>()
      1 # Concatenate the files
----> 2 concat_csv()

<ipython-input-109-9a5ae77e9dd8> in concat_csv()
     10         # Second file
     11         with open('new.csv') as f_read:
---> 12             f_read.next()
     13             for line in f_read:
     14                 f_out.write(line)

AttributeError: '_io.TextIOWrapper' object has no attribute 'next'

【问题讨论】:

    标签: python csv


    【解决方案1】:

    事实证明,在 Python 3 中,语法发生了变化。我们需要将其用作如下函数,而不是使用 next 作为方法:

    next(f_read)
    

    立即解决问题。

    【讨论】:

    • 更具体地说,迭代器有一个称为__next__ 的方法,而不是next,它在迭代器传递给next 函数时调用。这使其与其他协议保持一致(例如len 调用__len__ 等)。
    • 注意:The next function exists in 2.6 and higher,因此您可以在 2.6+ 和 3.x 上使用此代码。从 2 到 3 的实际变化是特殊方法的名称从 next 更改为 __next__ (以匹配其他特殊方法,并避免在 next 作为方法有意义但您的类不是迭代器时引起问题)。使用next 功能文件来解决该更改;它在两个版本上都能正常工作。
    猜你喜欢
    • 2021-05-31
    • 2014-01-16
    • 1970-01-01
    • 2015-08-16
    • 1970-01-01
    • 1970-01-01
    • 2022-11-06
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多