繁体   English   中英

在python 2.7中将字典写入csv文件

[英]Writing a dictionary to a csv file in python 2.7

我要编写一个如下所示的字典:{'2234':'1','233':'60'}到已创建的新csv文件中。 我找到了一个可以回答这个问题的页面,并在python 2.7中进行了尝试,但这在执行代码时仍然给我一个错误:

with open('variabelen.csv', 'w') as csvfile:
    writer = csv.writer(csvfile)  
    for name, items in a.items():    
        writer.writerow([name] + items)

当我执行代码时,这对我来说是一个错误:

Traceback (most recent call last):
  File "/Users/Danny/Desktop/Inventaris.py", line 48, in <module>
    Toevoeging_methode_plus(toevoegproduct, aantaltoevoeging)
  File "/Users/Danny/Desktop/Inventaris.py", line 9, in Toevoeging_methode_plus
    writecolumbs()
  File "/Users/Danny/Desktop/Inventaris.py", line 24, in writecolumbs
    writer.writerow([name] + items)
TypeError: can only concatenate list (not "str") to list

您正在将列表[name]与字符串items连接在一起-因此出错。

相反,您可以只通过.writerows()编写items() .writerows()

with open('variabelen.csv', 'w') as csvfile:
    writer = csv.writer(csvfile)
    writer.writerows(a.items())

给定a = {'2234': '1', '233': '60'} ,它将生成具有以下内容的variabelen.csv

233,60
2234,1

但是行的顺序可能会有所不同,这是因为Python中的字典是无序集合

暂无
暂无

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

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