如何将列表保存在.csv文件中的列而不是行中?

我想在.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)
评论
  • qquasi
    qquasi 回复

    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.

    如果要将每个项目写入其自己的行,则需要提供每个项目作为其自己的列表:

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

  • 占领网吧
    占领网吧 回复

    您是否尝试过通过以下方式替换writerows行:

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

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