你最可能需要的是DictReader
(正如布魯諾指出的那樣,他更快地拉動扳機)。它採用文件名並將每行作爲字典返回,這是您想要的。這將使你的代碼:
import csv
a = []
reader = csv.DictReader(open("so.csv",'rU'), dialect=csv.excel_tab, delimiter=',')
print reader
for row in reader:
print row
a.append(row)
print a[2]['Make']
任選簡化爲:
import csv
with open("so.csv",'rU') as f:
a = list(csv.DictReader(f, dialect=csv.excel_tab, delimiter=','))
print a[2]['Make']
使用一些樣本數據(從Wikipedia):
Year,Make,Model,Description,Price
1997,Ford,E350,"ac, abs, moon",3000.00
1999,Chevy,"Venture ""Extended Edition""","",4900.00
1999,Chevy,"Venture ""Extended Edition, Very Large""",,5000.00
1996,Jeep,Grand Cherokee,"MUST SELL!
air, moon roof, loaded",4799.00
打印:
<csv.DictReader instance at 0x7fe7a3aedfc8>
{'Price': '3000.00', 'Description': 'ac, abs, moon', 'Make': 'Ford', 'Model': 'E350', 'Year': '1997'}
{'Price': '4900.00', 'Description': '', 'Make': 'Chevy', 'Model': 'Venture "Extended Edition"', 'Year': '1999'}
{'Price': '5000.00', 'Description': '', 'Make': 'Chevy', 'Model': 'Venture "Extended Edition, Very Large"', 'Year': '1999'}
{'Price': '4799.00', 'Description': 'MUST SELL!\nair, moon roof, loaded', 'Make': 'Jeep', 'Model': 'Grand Cherokee', 'Year': '1996'}
Chevy
這個假設如果您的文件以這樣的標題開頭,則提供密鑰。如果沒有,你可以通過標題的列表中DictReader
:
reader = csv.DictReader(open("so.csv",'rU'), ["Year", "Make", "Model", "Description", "Price"], dialect=csv.excel_tab, delimiter=',')
還要注意的是隨地吐痰字符由delimiter=','
參數給出。
是什麼'打印一個[45] ['firstname']'應該在做什麼,你的數據是什麼樣的?行也是一個列表,所以它是有道理的,你不能分裂它 – 2014-12-05 15:13:05
你似乎不想使用數組,而是列表。 – user2097159 2014-12-05 15:14:23
你可能只想做'a.append(row)' – user2097159 2014-12-05 15:16:38