Search code examples
pythonlistcsvfwrite

write list to CSV


I have a list of lists like:

[[A], [B], [A,B], [B], [C], [A, B, C], [C, A]]

I want to write it to CSV file like:

A,
B,
A,B,
B,
C,
A,B,C,
C,A,

Please consider that I have 556,375 lists and each of them contains minimum 20 variables.


Solution

  • To add the extra comma, just add an empty cell at the end of each row.

    Here's a short way using generator comprehension within writerows

    import csv
    
    l = [["A"], ["B"], ["A","B"], ["B"], ["C"], ["A", "B", "C"], ["C", "A"]]
    
    with open("output.csv","w",newline="") as f:  # open("output.csv","wb") for Python 2
        cw = csv.writer(f)
        cw.writerows(r+[""] for r in l)