Python: Write two lists into two column text file

后端 未结 6 732
我寻月下人不归
我寻月下人不归 2020-12-13 07:23

Say I have two lists: a=[1,2,3] b=[4,5,6] I want to write them into a text file such that I obtain a two column text file:



        
6条回答
  •  悲哀的现实
    2020-12-13 07:46

    A simple solution is to write columns of fixed-width text:

    a=[1,2,3]
    b=[4,5,6]
    
    col_format = "{:<5}" * 2 + "\n"   # 2 left-justfied columns with 5 character width
    
    with open("foo.csv", 'w') as of:
        for x in zip(a, b):
            of.write(col_format.format(*x))
    

    Then cat foo.csv produces:

    1    4    
    2    5    
    3    6    
    

    The output is both human and machine readable, whereas tabs can generate messy looking output if the precision of the values varies along the column. It also avoids loading the separate csv and numpy libraries, but works with both lists and arrays.

提交回复
热议问题