2017-10-20 49 views
-1

我想把虹膜數據集放入一個列表中,但是當我嘗試讀取文件中的行時,它並未分隔每個值,而是將其放入1個字符串中。我如何解決這個問題,以便它打開並分離數據? 一些數據:python:csv文件不會把數據放入列表

sepal_length,sepal_width,petal_length,petal_width,species 
5.1,3.5,1.4,0.2,setosa 
4.9,3.0,1.4,0.2,setosa 
4.7,3.2,1.3,0.2,setosa 
4.6,3.1,1.5,0.2,setosa 
5.0,3.6,1.4,0.2,setosa 
5.4,3.9,1.7,0.4,setosa 
4.6,3.4,1.4,0.3,setosa 

代碼:

import csv 

with open("iris.csv", "r") as csv_iris: 
    read = csv.reader(csv_iris, delimiter = ",") 

    for line in csv_iris: 
     print(line[0]) 

輸出:

s 
5 
4 
4 
4 
5 
5 
4 

什麼輸出應該是:

sepal_length 
5.1 
4.9 
4.7 
4.6 
5.0 
5.4 
+2

你應該遍歷'read'(CSV閱讀器)對象。 '在線閱讀' –

回答

1

你被遍歷文件,而比csv reade河這導致每行的第一個字符被打印。

import csv 

with open("iris.csv", "r") as csv_iris: 
    read = csv.reader(csv_iris, delimiter = ",")  
    for line in read: 
     print(line[0]) 
0

我評論的錯誤

with open('iris.csv','r') as csv_iris: 
    read = csv.reader(csv_iris,delimiter=',') 
#Instead of calling for read, you called for csv_iris 
    for line in read: 
     print(line[0])