简体   繁体   中英

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

I am new to python, please help me resolve this.

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

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.

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'

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:

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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