繁体   English   中英

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

[英]Python: putting rows data from a csv file into a list

我在与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文件的每一行作为子列表返回,而不是将文件名的每个字母作为子列表返回。

您需要以读取模式打开文件,读取内容! 那是,

#!/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']]

您实际上需要open()文件:

inputfile = open('inputfile.csv')

您可能需要查看with语句:

with open('inputfile.csv') as inputfile:
    reader = csv.reader(inputfile)
    inputm = list(reader)

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM