简体   繁体   中英

Space between words when writing to csv

when I execute the below lines. I receive a space between each letter and the words do not format properly. any help is appreciated.

import csv
with open('u2.csv', 'w', newline='') as csvfile:
    wf = csv.writer(csvfile, delimiter = '\t')
    for key in wordcount.keys():
        wf.writerow("%s %s"  %(key, wordcount[key]))

When using Python's CSV library, the writerow() function takes a list and writes each element into the file with your chosen delimiter between each element. So you need to pass it a list. In your case, you need to create a list of two elements by enclosing the values in [ ] as follows:

import csv

wordcount = {'hello' : 2, 'world' : 5}

with open('u2.csv', 'w', newline='') as f_output:
    csv_output = csv.writer(f_output, delimiter='\t')

    for word, count in wordcount.items():
        csv_output.writerow([word, count])

This approach also avoids you having to lookup the count for each key.

You would get an output u2.csv looking like:

world   5
hello   2

I think this can help you:

import csv

Lists = [jassim, Greeshma, Abhirami, sourav]

with open ("name_list", "w", newline = ' ') as list:
    for names in Lists:
        Writer = CSV.writer(list , delimiter='\t')
        Writer.write(names)

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