Amit Goel
Amit Goel

Reputation: 35

How to write list contents to csv file as a single row

I have the following sample list:

sample_list = [['test1', 'test2'], ['am', 'cm']]

I want to write the above list to csv file. I'm using the following code for this:

with open('sample.csv', 'wb') as f_csv:
    writer = csv.writer(f_csv, delimiter=',', dialect='excel')
    writer.writerows(sample_list)
f_csv.close() 

The issue is that when I open sample.csv I see that test1, test2 are stored in separate columns, same for am , cm (stored in next row)

I need output in following form: Each sub-list to be listed in separate row and elements of sub-list in one column.

test1,test2
am,cm

Please can you help me in where i'm going wrong.

Upvotes: 0

Views: 1646

Answers (2)

Dimitris Fasarakis Hilliard
Dimitris Fasarakis Hilliard

Reputation: 160667

You need to change your list to include the comma , as a value in the converted string contents, if the list values can be of type int, convert them and then create the strings from the lists:

sample_list = [[",".join([str(item) for item in sub])] for sub in sample_list]

If we add a number to your original list, so:

sample_list = [['test1', 'test2', 392], ['am', 'cm']]

After the list comprehension, the list will be of the form:

sample_list = [['test1,test2,392'], ['am,cm']] 

Then, call writerows() on this list of lists:

with open('sample.csv', 'wb') as f_csv:
    writer = csv.writer(f_csv, delimiter=',', dialect='excel')
    writer.writerows(sample_list)

The output in sample.csv will be of the form:

"test1,test2,392"
"am,cm"

P.s You don't need to close f_csv. Using it with the with keyword takes care of that automatically.

Upvotes: 3

Martin Evans
Martin Evans

Reputation: 46779

The following script should produce one column per row:

import csv

sample_list = [['test1', 'test2', 1, 2], ['am', 'cm', 3, 4]]

with open('sample.csv', 'wb') as f_csv:
    writer = csv.writer(f_csv, dialect='excel')
    for sample in sample_list:
        writer.writerow([','.join(map(str, sample))])

Which creates a file as follows:

"test1,test2,1,2"
"am,cm,3,4"

When opened in Excel, this would give one column.

enter image description here

Upvotes: 0

Related Questions