首页 > 解决方案 > 使用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)

标签: pythonlistcsv

解决方案


这段代码对我有用,参考: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])

推荐阅读