user8471763
user8471763

Reputation:

Error in CSV Writing - Python

I'm running this code [self explanatory] :

import csv

word_list = ["Hello1;;;;World1", "Hello2;;;;World2"]

with open('words.csv', 'w') as new_file:
    csv_writer = csv.writer(new_file, delimiter=',')

    for line in word_list:
        csv_writer.writerow(line.split(';;;;')[0] + "\t" + line.split(';;;;')[1])

I'm expecting the csv to be :

Hello1, ,World1
Hello2, ,World2

I'm getting :

H,e,l,l,o,1,    ,W,o,r,l,d,1
H,e,l,l,o,2,    ,W,o,r,l,d,2

What's the error?

Upvotes: 1

Views: 36

Answers (1)

user9455968
user9455968

Reputation:

writerow takes an iterable. In your code this is the string build by

line.split(';;;;')[0] + "\t" + line.split(';;;;')[1]

This string is iterated, every item in it (= every character) is put into a cell.

Try

csv_writer.writerow([line.split(';;;;')[0], "\t", line.split(';;;;')[1]])

Upvotes: 3

Related Questions