迹忆客 专注技术分享

当前位置:主页 > 学无止境 > 编程语言 > Python >

Python 错误 AttributeError: _csv.reader Object Has No Attribute Next

作者:迹忆客 最近更新:2023/07/06 浏览次数:

CSV 格式是电子表格和数据库中最常用的格式之一。 Python 语言有 csv 模块,它提供了读取和写入 CSV 格式数据的类。

属性是与对象或类相关的值。 当您调用该方法不支持的类型的对象的属性时,Python 中会发生 AttributeError

例如,对文件对象使用 split() 方法会返回 AttributeError,因为文件对象不支持 split() 方法。

本篇文章将介绍如何修复 Python 中的 AttributeError: '_csv.reader' object has no attribute 'next'


修复 Python 中的 AttributeError: '_csv.reader' object has no attribute 'next' 错误

csv.reader 对象是一个迭代器。 next() 方法在 csv.reader 对象中可用,并返回可迭代对象的下一行。

import csv

with open(csvfile) as f:
    reader = csv.reader(f, delimiter=',', quotechar='"', skipinitialspace=True)
    header = reader.next()
    f.close()

输出:

line 5, in <module>
    header = reader.next()
AttributeError: '_csv.reader' object has no attribute 'next'

但在Python 3中,你必须使用内置函数 next(reader) 而不是 reader.next() 方法。

import csv

with open(csvfile) as f:
    reader = csv.reader(f, delimiter=',', quotechar='"', skipinitialspace=True)
    header = next(reader)
    f.close()

这样,Python 中的 AttributeError 就应该得到解决。 我们希望您觉得这篇文章有帮助。

转载请发邮件至 1244347461@qq.com 进行申请,经作者同意之后,转载请以链接形式注明出处

本文地址:

相关文章

Pandas read_csv()函数

发布时间:2024/04/24 浏览次数:254 分类:Python

Pandas read_csv()函数将指定的逗号分隔值(csv)文件读取到 DataFrame 中。

Pandas 追加数据到 CSV 中

发布时间:2024/04/24 浏览次数:352 分类:Python

本教程演示了如何在追加模式下使用 to_csv()向现有的 CSV 文件添加数据。

Pandas 多列合并

发布时间:2024/04/24 浏览次数:628 分类:Python

本教程介绍了如何在 Pandas 中使用 DataFrame.merge()方法合并两个 DataFrames。

Pandas loc vs iloc

发布时间:2024/04/24 浏览次数:837 分类:Python

本教程介绍了如何使用 Python 中的 loc 和 iloc 从 Pandas DataFrame 中过滤数据。

扫一扫阅读全部技术教程

社交账号
  • https://www.github.com/onmpw
  • qq:1244347461

最新推荐

教程更新

热门标签

扫码一下
查看教程更方便