Python:CSV按列写入,而不是按行 [英] Python: CSV write by column rather than row
问题描述
我有一个python脚本在while循环中生成一堆数据。
例如,在脚本的循环1中,我生成:
(1,2,3,4)
我需要这个在我的csv脚本中反映如下:
Result_1 1
Result_2 2
Result_3 3
Result_4 4
在我的第二个循环中,
(5,6,7,8)
我需要这个查看我的csv文件像这样:
Result_1 1 5
Result_2 2 6
Result_3 3 7
Result_4 4 8
等等,直到while循环结束。有人可以帮助我吗?
while循环可以持续超过100,000个循环
$ c> csv 不支持,因为大多数文件系统不支持可变长度行。你应该做的是收集列表中的所有数据,然后调用 zip()
在它们之后转置它们。
>>> l = [('Result_1','Result_2','Result_3','Result_4'),(1,2,3,4),(5,6,7,8)]
>> ; zip(* l)
[('Result_1',1,5),('Result_2',2,6),('Result_3',3,7),('Result_4',4,8)
I have a python script that generates a bunch of data in a while loop. I need to write this data to a CSV file, so it writes by column rather than row.
For example in loop 1 of my script I generate:
(1, 2, 3, 4)
I need this to reflect in my csv script like so:
Result_1 1
Result_2 2
Result_3 3
Result_4 4
On my second loop i generate:
(5, 6, 7, 8)
I need this to look in my csv file like so:
Result_1 1 5
Result_2 2 6
Result_3 3 7
Result_4 4 8
and so forth until the while loop finishes. Can anybody help me?
EDIT
The while loop can last over 100,000 loops
The reason csv
doesn't support that is because variable-length lines are not really supported on most filesystems. What you should do instead is collect all the data in lists, then call zip()
on them to transpose them after.
>>> l = [('Result_1', 'Result_2', 'Result_3', 'Result_4'), (1, 2, 3, 4), (5, 6, 7, 8)]
>>> zip(*l)
[('Result_1', 1, 5), ('Result_2', 2, 6), ('Result_3', 3, 7), ('Result_4', 4, 8)]
这篇关于Python:CSV按列写入,而不是按行的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!