Python:CSV 按列而不是按行写入 [英] Python: CSV write by column rather than row

查看:41
本文介绍了Python:CSV 按列而不是按行写入的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个 python 脚本,它在一个 while 循环中生成一堆数据.我需要将此数据写入 CSV 文件,因此它按列而不是按行写入.

例如在我生成的脚本的循环 1 中:

(1, 2, 3, 4)

我需要这样在我的 csv 脚本中反映出来:

Result_1 1结果_2 2结果_3 3结果_4 4

在我的第二个循环中,我生成:

(5, 6, 7, 8)

我需要这个来查看我的 csv 文件,如下所示:

Result_1 1 5结果_2 2 6结果_3 3 7结果_4 4 8

依此类推,直到 while 循环结束.有人可以帮我吗?


编辑

while 循环可以持续超过 100,000 次循环

解决方案

csv 不支持的原因是大多数文件系统并不真正支持可变长度行.您应该做的是收集列表中的所有数据,然后对它们调用 zip() 以将它们转置.

<预><代码>>>>l = [('Result_1', 'Result_2', 'Result_3', 'Result_4'), (1, 2, 3, 4), (5, 6, 7, 8)]>>>邮编(*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屋!

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