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

Time:08-25

I am facing an issue that 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 do 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 an item in the 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!

CodePudding user response:

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])

CodePudding user response:

Use writerows, for example:

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

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

CodePudding user response:

writerow() needs list with items (even when you have single item in row) but you use single string and it treads it as list of chars

You need

output_writer.writerow( [item] )
  • Related