gpt4 book ai didi

python - 类型错误 : '_csv.reader' object has no attribute '__getitem__' ?

转载 作者:太空狗 更新时间:2023-10-29 21:17:30 27 4
gpt4 key购买 nike

到目前为止,这是我的代码:

import csv
reader = csv.reader(open('new_file.txt','r'),delimiter=' ')
row1 = reader[0]
row2 = reader[1]
row3 = reader[2]

这是我的 new_file.txt:

this is row one
this is row two
this is row three

当我运行它时出现以下错误:

Traceback (most recent call last):
File "/home/me/Documents/folder/file.py", line 211, in <module>
row1 = reader[0]
TypeError: '_csv.reader' object has no attribute '__getitem__'

我该如何解决?

谢谢。

最佳答案

csv.reader() 对象不是序列。您不能按索引访问行。

为此,您必须将整个可迭代对象“吞噬”到一个列表中:

rows = list(reader)
row1 = rows[0]
row2 = rows[1]
row3 = rows[2]

这通常不是一个好主意。您可以改为使用 next() function 从迭代器中请求下一个值:

reader = csv.reader(open('new_file.txt','r'),delimiter=' ')
row1 = next(reader)
row2 = next(reader)
row3 = next(reader)

关于python - 类型错误 : '_csv.reader' object has no attribute '__getitem__' ?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/19090589/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com