Python: CSV write by column rather than row

后端 未结 7 968
春和景丽
春和景丽 2020-12-01 03:46

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

7条回答
  •  一向
    一向 (楼主)
    2020-12-01 04:17

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

提交回复
热议问题