Josav12
Josav12

Reputation: 27

Formatting from python 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 tabs or spaces. When I try:

with open(datafile, 'w', newline='', encoding='utf8') as csvfile:
    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(','.join(row))

I am looking for the output in the csv file to look like. 2017-03-07, 36939142. But instead in outputs this: 2 0 1 7 - 0 3 - 0 7 and the order number 3 6 9 3 9 1 4 2.

With spaces/tabs in between each character. This makes it impossible to use many of the excel functions.

How can I get the expected output in the csv file?

Upvotes: 0

Views: 231

Answers (2)

Endyd
Endyd

Reputation: 1279

Your problem is in the delimiter and the parameter with which you call writerow(). csv module already handles delimiting your columns for you, so you don't need to format your row with ','.join(row). What happened in your code was that you passed a string '2017-03-07,36939142' into the function writerow() which expects a list (as mentioned by @JordanSinger) . So then it took the string and cast it into a list, which becomes ['2', '0', '1', '7', '-', etc]. Then the delimiter was a '\t', so the csv writer took each character of your string created from the ','.join(row) and put a tab in between every character (as if each char is its own column, separated by tabs). So you want to change your delimiter as well as change the function call to writerow to pass a list, not a string.

Also, you can cut down the code by unpacking your dictionary into tuples of (key, value) pairs instead of iterating through the keys.

dic = {'2017-03-07': '36939142', '2014-02-19': '13193909'}

with open(datafile, 'w', newline='', encoding='utf8') as csvfile:
    datawriter = csv.writer(csvfile, delimiter=',')
    for date,order_number in dic.items():
        datawriter.writerow([date,order_number])

Output:

2017-03-07,36939142
2014-02-19,13193909

Upvotes: 2

Adam Smith
Adam Smith

Reputation: 1

Try this:

with open(datafile, 'w', newline='', encoding='utf8') as csvfile:
    datawriter = csv.writer(csvfile, delimiter=',')
    dic = {'2017-03-07': '36939142', '2014-02-19': '13193909'}

    for key, value in dic.items():
        row = [key, value]
        datawriter.writerow(row)

Upvotes: 0

Related Questions