TypeError:'_ csv.reader'对象没有属性'__getitem__'?

时间:2013-09-30 09:20:31

标签: python csv

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

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__'

我该如何解决?

感谢。

2 个答案:

答案 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]