在csv的第一列中编写输出

时间:2012-12-20 11:35:24

标签: python csv

我有数字序列:

  

6577

我希望在.csv文件中看到它们:

6  
5  
7

我已尝试使用文件编写器,但它会将所有数字写入第一行。

序列是字符串..

s = ['6','5','7','7','6']
item_length = len(s)

with open('test.csv', 'wb') as test_file:
    file_writer = csv.writer(test_file)
    for i in range(item_length):
        file_writer.writerow([x[i] for x in s])

1 个答案:

答案 0 :(得分:2)

如果您希望将每个列表项作为一行编写,可以尝试:

s = ['6','5','7','7','6']
item_length = len(s)

with open('test.csv', 'wb') as test_file:
    file_writer = csv.writer(test_file)
    for item in s:
        file_writer.writerow(item)

此外,只需要写出一列,这可能就足够了:

s = ['6','5','7','7','6']
with open('test.csv', 'wb') as test_file:
   test_file.write("\n".join(s) + "\n")