我想在.csv中保存一个列表。我有语法,但是它保存在行而不是列中。请提出建议。提前致谢。 我的语法是:
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)
我想在.csv中保存一个列表。我有语法,但是它保存在行而不是列中。请提出建议。提前致谢。 我的语法是:
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)
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.如果要将每个项目写入其自己的行,则需要提供每个项目作为其自己的列表:
Here, I've taken out the
[]
aroundx
in the last line and moved them intox.append([n])
to createx
that is[[1], [2], [3], [4], [5], [6], [7], [8], [9], [10]]
您是否尝试过通过以下方式替换writerows行:
It should work. (you should
import numpy as np
, of course)