Python, transposing a list and writing to a CSV file

后端 未结 3 978
时光取名叫无心
时光取名叫无心 2020-12-13 20:52

I need to write into a csv file using python and each iterator item should start in a new line. So delimiter I am using is \"\\n\". After each list has been written,next lis

相关标签:
3条回答
  • 2020-12-13 21:34

    first transpose your input by using zip()

    >>> zip(*lol)
    [(1, 4), (2, 5), (3, 6)]
    

    and after that just pass it to csw.writer e.g.

    with open("test.csv", "wb") as f:
        fileWriter = csv.writer(f, delimiter=',',quotechar='|', quoting=csv.QUOTE_MINIMAL)
        for row in zip(*lol):
            fileWriter.writerow(row)
    

    ... which results to:

    $ cat test.csv 
    1,4
    2,5
    3,6
    
    0 讨论(0)
  • 2020-12-13 21:50

    If you are using Python3 you need to open files in text format "wt", more over csv has writerows that can be used to write everything at once. here is an example:

    data=[("test", "value1", "value2"), ("test2", "value3", "value4")]
    with open('my.csv','wt') as out:
       csv_out=csv.writer(out)
       csv_out.writerows(data)
    

    I've just noticed that the question ask how to transform the list, that is a separate step and here is how I would do it:

    lol = [[1,2,3],[4,5,6]]
    data = zip(lol[0],lol[1])
    
    0 讨论(0)
  • 2020-12-13 21:53

    Without using zip, you could do this:

    import csv
    
    lol = [[1,2,3],[4,5,6],[7,8,9]]
    item_length = len(lol[0])
    
    with open('test.csv', 'wb') as test_file:
      file_writer = csv.writer(test_file)
      for i in range(item_length):
        file_writer.writerow([x[i] for x in lol])
    

    This will output into test.csv:

    1,4,7
    2,5,8
    3,6,9
    
    0 讨论(0)
提交回复
热议问题