[英]Python: putting rows data from a csv file into a list
I have a CSV file in the same directory as my Python script, and I would like to take that data and turn it into a list that I can use later. 我在与Python脚本相同的目录中有一个CSV文件,我想获取该数据并将其转换为列表,以便以后使用。 I would prefer to use Python's CSV module.
我更喜欢使用Python的CSV模块。 After reading the the module's documentation and questions regarding it, I have still not found any help.
在阅读了该模块的文档和有关该模块的问题之后,我仍然没有找到任何帮助。
#!/usr/bin/env python
# -*- coding: utf-8 -*-
import csv
inputfile = 'inputfile.csv'
inputm = []
reader = csv.reader(inputfile)
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
It only returns the string of the filename I provide it. 它仅返回我提供的文件名的字符串。
[['i'], ['n'], ['p'], ['u'], ['t'], ['f'], ['i'], ['l'], ['e']]
I would like it to return each row of the CSV file as a sub-list instead of each letter of the filename as a sub-list. 我希望将CSV文件的每一行作为子列表返回,而不是将文件名的每个字母作为子列表返回。
You need to open the file in read mode, read the contents! 您需要以读取模式打开文件,读取内容! That is,
那是,
#!/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)
Output: 输出:
[['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']]
You actually need to open()
the file: 您实际上需要
open()
文件:
inputfile = open('inputfile.csv')
You may want to look at the with
statement: 您可能需要查看
with
语句:
with open('inputfile.csv') as inputfile:
reader = csv.reader(inputfile)
inputm = list(reader)
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.