pythonpython-3.xlistcsvwriter

Cannot join chars into string in csv writer


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"
...

Solution

  • 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()