Cannot join chars into string in csv writer

Question:

I want to save my result into csv file. This is my code:

import itertools
import csv

letters = "ABCDEFGHIJKLMNOPQRSTUVWXYZ"

combinations = list(itertools.permutations(letters, 4))
print(len(combinations))

with open('result.csv', 'w', newline='') as myfile:
    wr = csv.writer(myfile, quoting=csv.QUOTE_ALL)
    for item in combinations:
        wr.writerow("".join(item))
    myfile.close()

the .csv result is:

"A","B","C","D"
"A","B","C","E"
"A","B","C","F"
...

what I expect is:

"ABCD"
"ABCE"
"ABCF"
...

I am new in python but I don’t know why this occur, because when I write "".join(item) in the loop, I got what I want. Can you help me?

what i expect is:

"ABCD"
"ABCE"
"ABCF"
...
Asked By: Alfian Khusnul

||

Answers:

The issue is that you are passing a string to writerow instead of a list. To fix this, you can wrap "".join(item) inside a list before passing it to writerow. Here’s the modified code:

import itertools
import csv

letters = "ABCDEFGHIJKLMNOPQRSTUVWXYZ"

combinations = list(itertools.permutations(letters, 4))
print(len(combinations))

with open('result.csv', 'w', newline='') as myfile:
    wr = csv.writer(myfile, quoting=csv.QUOTE_ALL)
    for item in combinations:
        wr.writerow(["".join(item)]) # wrap "".join(item) inside a list
    myfile.close()

This should give you the desired output in the CSV file.

Answered By: Akai

writerow() interprets the string you pass as a sequence of characters. This causes the function to write each character as a separate field. Instead of passing "".join(item) you can pass ["".join(item)] to treat them as a single field

import itertools
import csv

letters = "ABCDEFGHIJKLMNOPQRSTUVWXYZ"

combinations = list(itertools.permutations(letters, 4))
print(len(combinations))

with open('result.csv', 'w', newline='') as myfile:
    wr = csv.writer(myfile, quoting=csv.QUOTE_ALL)
    for item in combinations:
        wr.writerow(["".join(item)])
    myfile.close()
Answered By: Isuru
Categories: questions Tags: , , ,
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.