[英]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.