Writing a CSV horizontally

前端 未结 2 1952
逝去的感伤
逝去的感伤 2021-01-17 00:26

Say we are reading data from some source with multiple key-value pairs. Let\'s use the following list as an example:

[{\'key0\': \'key0_value0\', \'key1\': \         


        
2条回答
  •  隐瞒了意图╮
    2021-01-17 01:01

    There is no way to write columns progressively, because that's not how text files (which CSV files are a subset of) work. You can't append to a line/row in the middle of a file; all you can do is append new lines at the end.

    However, I'm not sure why you need to do this anyway. Just transpose the list in-memory, then write it row by row.

    For example:

    values = [{'key0': 'key0_value0', 'key1': 'key1_value0'},
              {'key0': 'key0_value1', 'key1': 'key1_value1'}]
    transposed = zip(*(x.items() for x in values))
    grouped = ([pairs[0][0]] + [pair[1] for pair in pairs] for pairs in transposed)
    writer.writerows(grouped)
    

    Just transposing the items isn't quite enough, because you end up with a copy of key0 for each value, instead of just one copy. That's what the grouped is for.

提交回复
热议问题