rrcmks
rrcmks

Reputation: 1

How to save list in column in .csv file instead of rows?

I want to save a list in .csv. I had syntax, but it save in rows instead of columns. Please give suggestion. Thanks in advance. My syntax is:

import csv
n=0
x=[]
while n < 10:
    n = n+1
    x.append(n)
with open('test.csv','w') as file:
    writer = csv.writer(file)
    writer.writerows([x])
print(x)

Upvotes: 0

Views: 734

Answers (3)

martineau
martineau

Reputation: 123463

You need to pass the csv.writerows() method an "an iterable of row objects", which can be a generator expression. Also note you should open csv files with newline='' in Python 3.x as shown in the module's documentation.

Here's how to do it. Note how each value in the list is (temporarily) turned into a list of one item by the [v] part of the expression.

import csv

x = list(range(10))

with open('testfile.csv', 'w', newline='') as file:
    csv.writer(file).writerows(([v] for v in x))

print('done')

Upvotes: 0

Hamatti
Hamatti

Reputation: 1220

The way writerows functions is that it takes an iterable (in this case, a list) and prints each item on that iterable on its own line, separated by delimiter (by default, a ,)

What happens here is that you're passing [[1,2,3,4,5,6,7,8,9,10]] which means there is a single row ([1,2,3,4,5,6,7,8,9,10]) to be written out.

If you want to write each item to it's own row, you need to provide each item as its own list:

import csv
n = 0
x = []
while n < 10:
    n = n+1
    x.append([n])

print(x)
with open('test.csv', 'w') as file:
    writer = csv.writer(file)
    writer.writerows(x)

Here, I've taken out the [] around x in the last line and moved them into x.append([n]) to create x that is [[1], [2], [3], [4], [5], [6], [7], [8], [9], [10]]

Upvotes: 1

Igor Rivin
Igor Rivin

Reputation: 4864

Have you tried replacing the writerows line by:

writer.writerows(np.array([x]).T)

It should work. (you should import numpy as np, of course)

Upvotes: 0

Related Questions