Search code examples
pythonfilecsvfile-iopython-2.7

Writing a Python list of lists to a csv file


I have a long list of lists of the following form ---

a = [[1.2,'abc',3],[1.2,'werew',4],........,[1.4,'qew',2]]

i.e. the values in the list are of different types -- float,int, strings.How do I write it into a csv file so that my output csv file looks like

1.2,abc,3
1.2,werew,4
.
.
.
1.4,qew,2

Solution

  • Python's built-in csv module can handle this easily:

    import csv
    
    with open('out.csv', 'w', newline='') as f:
        writer = csv.writer(f)
        writer.writerows(a)
    

    This assumes your list is defined as a, as it is in your question. You can tweak the exact format of the output CSV via the various optional parameters to csv.writer().