Python:将csv文件中的行数据放入列表中

时间:2017-03-27 03:40:24

标签: python python-2.7 list csv

我在与Python脚本相同的目录中有一个CSV文件,我想把这些数据转换成一个我以后可以使用的列表。我更喜欢使用Python的CSV模块。在阅读了模块的文档和有关它的问题之后,我仍然没有找到任何帮助。

代码

#!/usr/bin/env python
# -*- coding: utf-8 -*-
import csv
inputfile = 'inputfile.csv'

inputm = []

reader = csv.reader(inputfile)

for row in reader:
    inputm.append(row)

inputfile.csv

point1,point2,point3,point4
0,1,4,1 
0,1,1,1 
0,1,4,1 
0,1,0,0
0,1,2,1 
0,0,0,0 
0,0,0,0 
0,1,3,1 
0,1,4,1

它只返回我提供的文件名的字符串。

[['i'], ['n'], ['p'], ['u'], ['t'], ['f'], ['i'], ['l'], ['e']]

我希望将CSV文件的每一行作为子列表返回,而不是将文件名的每个字母作为子列表返回。

2 个答案:

答案 0 :(得分:3)

您需要以读取模式打开文件,阅读内容! 也就是说,

#!/usr/bin/env python
# -*- coding: utf-8 -*-
import csv
inputfile = 'inputfile.csv'

inputm = []

with open(inputfile, "rb") as f:
    reader = csv.reader(f, delimiter="\t")
    for row in reader:
        inputm.append(row)

输出:

[['point1,point2,point3,point4'], ['0,1,4,1'], ['0,1,1,1'], ['0,1,4,1'], ['0,1,0,0'], ['0,1,2,1'], ['0,0,0,0'], ['0,0,0,0'], ['0,1,3,1'], ['0,1,4,1']]

答案 1 :(得分:1)

您确实需要open()该文件:

inputfile = open('inputfile.csv')

您可能需要查看with声明:

with open('inputfile.csv') as inputfile:
    reader = csv.reader(inputfile)
    inputm = list(reader)
相关问题