使用python将列表存储到csv文件中

时间:2016-06-07 11:15:20

标签: python csv

我正在尝试使用python将类型列表变量存储到csv文件中。以下是我在StackOverflow和python文档中获得的数据:

代码:

row = {'SgDescription': 'some group', 'SgName': 'sku', 'SgGroupId': u'sg-abcdefgh'}
new_csv_file = open("new_file.csv",'wb')
ruleswriter = csv.writer(new_csv_file,dialect='excel',delimiter=',')
ruleswriter.writerows(row)
new_csv_file.close()

结果:

$ more new_file.csv 
S,g,D,e,s,c,r,i,p,t,i,o,n
S,g,N,a,m,e
S,g,G,r,o,u,p,I,d

任何人都可以建议如何将值存储到文件中,如下所示:

some group,sku,sg-abcdefgh

非常感谢!

2 个答案:

答案 0 :(得分:1)

在写入csv文件之前提取所需数据

row = [row['SgDescription'], row['SgName'], row['SgGroupId']]       # ['some group', 'sku', u'sg-abcdefgh']


# write to a csv file
with open("new_file.csv",'wb') as f:
    ruleswriter = csv.writer(f)
    ruleswriter.writerow(row)

PS:如果您不关心订单,只需使用row.values()

或使用csv.DictWriter

import csv

row = {'SgDescription': 'some group', 'SgName': 'sku', 'SgGroupId': u'sg-abcdefgh'}
with open('new_file.csv', 'w') as csvfile:
    fieldnames = ['SgDescription', 'SgName', 'SgGroupId']
    writer = csv.DictWriter(csvfile, fieldnames=fieldnames)
    writer.writerow(row)

答案 1 :(得分:1)

writerows()需要一系列序列,例如列表列表。你在dict中传递,dict碰巧是可迭代的:它返回字典的键。每个键 - 一个字符串 - 碰巧也是可迭代的。所以你得到的是每个单元格中每个可迭代的元素,这是一个字符。你得到了你所要求的: - )

你想要做的是写一行,其中包含键,然后是另一行的值,例如:

import csv

row = {
    'SgDescription': 'some group',
    'SgName': 'sku',
    'SgGroupId': u'sg-abcdefgh'
}


with open("new_file.csv",'wb') as f:
    ruleswriter = csv.writer(f)
    ruleswriter.writerows([row.keys(), row.values()])

如果订单很重要,请使用collections.OrderedDict