1

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!

3 Answers 3

2

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])
Sign up to request clarification or add additional context in comments.

2 Comments

perfect thanks a lot it's working! so if i put the item of the list into a variable and use [], the whole payload of the variable is considered as 1 element?
@Samurajx Yes, in your case each item is a string. So if you enclose it in [], you now have a list (an iterable) of strings of length 1. The item string is then considered one element. I would appreciate if you marked the answer as accepted, if it helped you.
1

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)

Comments

1

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

2 Comments

No, it doesn't need a list. Any iterable works. Also char is not a thing in Python. The single string is an iterable of strings.
@DaniilFajnberg frankly, it is not important details to solve problem. And list of chars can be more readable for beginners.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.