Josav12
Josav12

Reputation: 27

Formatting strings to csv

I am trying to write keys and values from a dictionary in python to a csv file. I am getting the write output but I want to format it so it does not contain any '[]' or '"'. When I try:

with open(datafile, 'w', newline='', encoding='utf8') as csvfile:
    # Tab delimited to allow for special characters
    datawriter = csv.writer(csvfile, delimiter='\t')
    dic = {'2017-03-07': '36939142', '2014-02-19': '13193909'}
    for key in dic.keys():
        date = key
        order_number = dic[key]
        row = [date, order_number]
        datawriter.writerow([row])

I am looking for the output in the csv file to look like. 2017-03-07, 36939142. But instead in outputs this: ['2017-03-07, '36939142'].

How can I format it so I get the expected output?

Upvotes: 1

Views: 1825

Answers (4)

Haseeb Asif
Haseeb Asif

Reputation: 1786

In python 3 you can achieve it as follows

with open(datafile, 'w', newline='', encoding='utf8') as csvfile:
    # Tab delimited to allow for special characters
    datawriter = csv.writer(csvfile, delimiter='\t')
    dic = {'2017-03-07': '36939142', '2014-02-19': '13193909'}
    for key,value in dic.items():
        datawriter.writerow("{0}, {1}".format(key,value))

Upvotes: 0

Felix
Felix

Reputation: 1905

If you want to stay with your solution you can change the last but one line to

row = f"{date}, {order_number}"

Upvotes: 0

Calvin Godfrey
Calvin Godfrey

Reputation: 2359

Try datawriter.writerow(', '.join(row)) as the last line. Right now you're writing the data to the csv file as an array. The ', '.join(ar) syntax takes each part of the array in parenthesis and concatenates them together with a comma in between them

Upvotes: 2

Umair Mohammad
Umair Mohammad

Reputation: 4635

Try something like this :

with open(datafile, 'w', newline='', encoding='utf8') as csvfile:
    # Tab delimited to allow for special characters
    datawriter = csv.writer(csvfile, delimiter='\t')
    dic = {'2017-03-07': '36939142', '2014-02-19': '13193909'}
    for key in dic.keys():
        datawriter.writerow("%s, %s" % (key, dic[key]))

Upvotes: 0

Related Questions