Writing strings to CSV causing issue where the string in CSV is separated by commas (Python)

i am facing an issue which i was not able to resolve so far. I need to save a list of strings into the CSV file. I am able to do it however the strings from each element of the list are separated by commas. Why is that and what i need to do to resolve this issue? Sorry for maybe simple question i am new to programming. I know it has to be somehow related to the string properties where each number is similar to item in list and is indexed however i was not able to find the cause of this behavior and how to resolve it.

Here is the code:

duplicity = ['8110278643', '8110278830', '8110283186']

with open("duplicty.csv", "w", newline="") as duplicity_csv:
    output_writer = csv.writer(duplicity_csv)
    header = ["Number"]
    output_writer.writerow(header)
    for item in duplicity:
        output_writer.writerow(item)

The output of this code in CSV is following:

Number
8,1,1,0,2,7,8,6,4,3
8,1,1,0,2,7,8,8,3,0
8,1,1,0,2,8,3,1,8,6

The expected output should be:

Number
8110278643
8110278830
8110283186

Thanks a lot for your replies!

>Solution :

The writerow method takes an iterable of strings. Each item in your list is in fact an iterable — namely a string. Each element from that iterable (in your case each letter in the string) is taken as its own element in a sperate column.

You could just do this instead:

...
    for item in duplicity:
        output_writer.writerow([item])

Leave a Reply