以下是我的CSV文件:
id, lastname, firstname, product, cost
1, Smith, III, Jon, iPad, 400
2, Green, Jane, iPhone, 500
所需的输出将是:
[[1, Smith III, Jon, iPad, 400], [2, Green, Jane, iPhone, 500]]
我已尝试通过以下方法完成此任务:
main_list = []
with open(filepath, 'r') as f:
next(f)
for rows in f:
main_list.append(rows.strip().split(','))
csv.reader()
,但是它没有工作。有什么建议吗?
答案 0 :(得分:0)
这里有一个csv解析器,我把它做成字典的字典,按第一个值(id)排序,其中键是类别(id,lastname等),如果那还不行的话,
import csv
def parseCsvFile (dataFile):
dict = {}
with open(dataFile) as csvfile:
reader = csv.DictReader(csvfile)
for row in reader:
key = None
for k in row:
stripK = k.strip()
stripV = row[k].strip()
if key == None:
key = stripV
dict[key] = {}
dict[key][stripK] = stripV
return dict