到目前为止,这是我的代码:
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__'
我该如何解决?
感谢。
答案 0 :(得分:16)
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)
答案 1 :(得分:2)
您可以循环reader
,然后访问row
元素:
import csv
reader = csv.reader(open('new_file.txt','r'),delimiter=' ')
for row in reader:
row1 = row[0]
row2 = row[1]
row3 = row[3]