我正在尝试将虹膜数据集放入列表中,但是当我尝试读取文件中的行时,它不会将每个值分开,而是将其放入1个字符串中。我如何解决这个问题,以便打开并分离数据? 一些数据:
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
答案 0 :(得分:1)
您正在迭代文件而不是csv阅读器。这导致每行的第一个字符被打印出来。
import csv
with open("iris.csv", "r") as csv_iris:
read = csv.reader(csv_iris, delimiter = ",")
for line in read:
print(line[0])
答案 1 :(得分: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])