Skip to main content
 首页 » 编程设计

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

2024年10月17日6xiaohuochai

我正在尝试使用 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 

非常感谢!

请您参考如下方法:

writerows() 需要一系列序列,例如列表列表。您正在传递一个字典,而这个字典恰好是可迭代的:它返回字典的键。每个键——一个字符串——恰好也是可迭代的。所以你得到的是每个单元格的每个可迭代的元素,这是一个字符。你得到了你想要的:-)

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

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。