Python 错误 AttributeError: _csv.reader Object Has No Attribute Next
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 就应该得到解决。 我们希望您觉得这篇文章有帮助。
相关文章
Pandas DataFrame DataFrame.shift() 函数
发布时间:2024/04/24 浏览次数:133 分类:Python
-
DataFrame.shift() 函数是将 DataFrame 的索引按指定的周期数进行移位。
Python pandas.pivot_table() 函数
发布时间:2024/04/24 浏览次数:82 分类:Python
-
Python Pandas pivot_table()函数通过对数据进行汇总,避免了数据的重复。
Pandas read_csv()函数
发布时间:2024/04/24 浏览次数:254 分类:Python
-
Pandas read_csv()函数将指定的逗号分隔值(csv)文件读取到 DataFrame 中。
Pandas 多列合并
发布时间:2024/04/24 浏览次数:628 分类:Python
-
本教程介绍了如何在 Pandas 中使用 DataFrame.merge()方法合并两个 DataFrames。
Pandas loc vs iloc
发布时间:2024/04/24 浏览次数:837 分类:Python
-
本教程介绍了如何使用 Python 中的 loc 和 iloc 从 Pandas DataFrame 中过滤数据。
在 Python 中将 Pandas 系列的日期时间转换为字符串
发布时间:2024/04/24 浏览次数:894 分类:Python
-
了解如何在 Python 中将 Pandas 系列日期时间转换为字符串