如何从列表中的列和行从csv文件中写数据? [英] How do I write data to csv file in columns and rows from a list in python?

查看:454
本文介绍了如何从列表中的列和行从csv文件中写数据?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

everyone.我有一个列表的列表,我想把它们写在一个csv文件与列和行。我已经尝试了writerows,但它不是我想要的。我的列表的一个示例是以下: / p>

  [[1,2],[2,3],[4,5]] 



感谢任何帮助。




$ b

  example = csv.writer(open('test.csv','wb'),delimiter ='')
example.writerows [[1,2],[2,3],[4,5]])



在单元格中获得1 2,在单元格中有2 3等。在单元格中不是1,在下一单元格中是2。



我应该更清楚。需要把这个例子列表写到一个文件,所以当我打开它与excel每个元素都在自己的单元格。
我的输出应该是这样:

  1 2 
2 3
4 5

不同单元格中的每个元素。

解决方案

提供的示例,使用 csv 模块,是伟大的!此外,您可以随时使用格式化的字符串写入一个文本文件,如下面的例子:

  l = [[1 ,2],[2,3],[4,5]] 

out = open('out.csv','w')
b for row in row:
out.write('%d;'%column)
out.write('\\\
')
out.close()

我使用; 作为分隔符,您的要求之一)。



希望它有帮助!


everyone.I have a list of lists and I want to write them in a csv file with columns and rows.I have tried the writerows but it isn't what I want.An example of my list is the following:

[[1, 2], [2, 3], [4, 5]]

Thanks for any help.

With this :

example=csv.writer(open('test.csv', 'wb'), delimiter=' ')
example.writerows( [[1, 2], [2, 3], [4, 5]])

I get 1 2 in a cell,2 3 in a cell etc.And not 1 in a cell and 2 in the next cell.

I should have been more clear.I need to write this example list to a file so when I open it with excel every element is in its own cell. My output should be like this:

1 2
2 3
4 5

Each element in diferent cell.

解决方案

The provided examples, using csv modules, are great! Besides, you can always simply write to a text file using formatted strings, like the following tentative example:

l = [[1, 2], [2, 3], [4, 5]]

out = open('out.csv', 'w')
for row in l:
    for column in row:
        out.write('%d;' % column)
    out.write('\n')
out.close()

I used ; as separator, because it works best with Excell (one of your requirements).

Hope it helps!

这篇关于如何从列表中的列和行从csv文件中写数据?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆