2016-11-19 87 views
-1
串皈依

我有一個car.csv,其中有這樣的臺詞:讀csv文件到列表中的列表,而在Python

vhigh,vhigh,2,2,small,low,unacc 

我想:

[vhigh,vhigh,2,2,small,low,unacc]. 

但隨着這個代碼

import csv 
a = [] 
with open("car.csv", 'r') as f: 
    reader = csv.reader(f) 
    for line in f: 
     a.append([line]); 

我得到

['vhigh,vhigh,2,2,small,med,unacc\n']. 

有人可以幫我嗎?

+0

我並不知道[vhigh,vhigh,2,2,small,low,unacc]與['vhigh','vhigh','2','2','small' ,'low','unacc'] – kassio

回答

2

當您創建讀者,迭代是,而不是通過文件,以便做到:

for line in reader: 
    a.append(line) 

,或者如果你只是想所有行作爲一個列表

a = list(reader) 

把所有在一起:

with open("car.csv", "r") as f: 
    reader = csv.reader(f) 
    a = list(reader) 
-1

分割線的內容

line.split(',') 
+2

如果CSV中的某個字段包含逗號,該怎麼辦? –