2013-09-30 198 views
6

這裏是我到目前爲止的代碼:TypeError:'_csv.reader'對象沒有屬性'__getitem__'?

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

我怎樣才能解決這個問題?

謝謝。

回答

16

A csv.reader() object is not a sequence。您不能通過索引訪問行。

你不得不「啜食」整個迭代到一個列表爲:

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) 
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] 
相關問題