简体   繁体   English

使用for循环在csv文件中写入键和值— python

[英]write key and values in csv file using for loop — python

I am new to python, please help me resolve this. 我是python的新手,请帮助我解决这个问题。

My code looks like: 我的代码如下:

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')

I want to insert data into csv instead of printing 我想将数据插入到csv中而不是打印

like this: 像这样:

A,B,C
sometext,some,text
xhbasj,bjascn,bashc
bhhashc,bashjc,bcsahbch
cvashcj,bcashc,bcasc

here A,B,C will be like keys. 这里的A,B,C就像钥匙。

I have tried many options but none of them working, please help me resolve this 我尝试了很多选择,但没有一个起作用,请帮助我解决这个问题

I have tried this 我已经试过了

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)

This code worked for me, referred: Python: Writing a dictionary to a csv file with one line for every 'key: value' 这段代码对我有用,请参阅: Python:将字典写入csv文件,每个“键:值”一行

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])

Open file for writing and get a csv writer: 打开文件进行写入并获取csv编写器:

import csv
with open('my_file.csv', mode='w') as f:
    csv_writer = csv.writer(f, delimiter=',', quotechar='"', quoting=csv.QUOTE_MINIMAL)

Then write you top keys: 然后写下您的重要关键字:

csv_writer.writerow(['A', 'B', 'C'])

Then do your loop 然后做你的循环

for ...

And in there write you code: 然后在其中编写代码:

if div == 0 or div == 1 or div == 2:
      csv_writer.writerow(['sometext', 'some', 'text']
...

example: 例:

import csv

with open('my_file.csv', mode='w') as f:
    csv_writer = csv.writer(f, delimiter=',', quotechar='"', quoting=csv.QUOTE_MINIMAL)
    csv_writer.writerow(['A', 'B', 'C'])
    for i in range(10):
        csv_writer.writerow(['i', i, 10-i])

Will write the following file: 将写入以下文件:

A,B,C
i,0,10
i,1,9
i,2,8
i,3,7
i,4,6
i,5,5
i,6,4
i,7,3
i,8,2
i,9,1

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

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