python - 使用for循环在csv文件中写入键和值——python
问题描述
我是python新手,请帮我解决这个问题。
我的代码如下所示:
if div == 0 or div == 1 or div == 2:
print (' A ', 'sometext')
elif div == 5 or div == 6:
print (' B ', 'some')
elif div == 3 or div == 4:
print (' C ', 'text')
我想将数据插入 csv 而不是打印
像这样:
A,B,C
sometext,some,text
xhbasj,bjascn,bashc
bhhashc,bashjc,bcsahbch
cvashcj,bcashc,bcasc
这里 A,B,C 就像键。
我尝试了很多选项,但都没有工作,请帮我解决这个问题
我试过这个
with open('trashData.csv', 'w', newline='') as fp:
a = csv.writer(fp, delimiter=',')
if div == 0 or div == 1 or div == 2:
data = [['A'],['sometext']]
a.writerows(data)
解决方案
这段代码对我有用,参考:Python: Writing a dictionary to a csv file with one line for each 'key: value'
import csv
dictionary = {'A':'Text', 'B':'Sometext'}
f = open('dictionary.csv', 'w+')
writer = csv.writer(f)
for k,v in dictionary.items():
writer.writerow([k,v])
推荐阅读
- javascript - 以编程方式添加对象时如何从对象数组中键入属性
- python - django.core.exceptions.ImproperlyConfigured。来自 django 初学者的 SOS
- reactjs - 如何在 Gatsby 中查询特定语言的 markdown 文件?
- react-redux - 商店未定义 react-redux
- python - 有没有办法预测 exp 是否会返回 inf
- android - CardStackView.Rewind() 在片段中不起作用
- ruby - 如何在 Google API (Ruby) WebmastersV3 中使用身份验证令牌(服务帐户访问)
- javascript - JavaScript noob - 在没有“window.location”的情况下传递 GET 数据
- java - 如何删除字符串末尾和开头的特殊字符
- javascript - 如何将 ng-bind 设置为从 angular http 返回的值?