The Python Oracle

Writing a Python list of lists to a csv file

Become part of the top 3% of the developers by applying to Toptal https://topt.al/25cXVn

--

Music by Eric Matyas
https://www.soundimage.org
Track title: Puzzle Game Looping

--

Chapters
00:00 Question
00:30 Accepted answer (Score 412)
01:11 Answer 2 (Score 46)
01:26 Answer 3 (Score 42)
01:46 Answer 4 (Score 14)
02:26 Thank you

--

Full question
https://stackoverflow.com/questions/1403...

Accepted answer links:
[CSV module]: http://docs.python.org/2/library/csv.htm...

Answer 3 links:
http://docs.python.org/2/library/csv.htm...

--

Content licensed under CC BY-SA
https://meta.stackexchange.com/help/lice...

--

Tags
#python #file #csv #fileio #python27

#avk47



ACCEPTED ANSWER

Score 430


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().




ANSWER 2

Score 51


You could use pandas:

In [1]: import pandas as pd

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

In [3]: my_df = pd.DataFrame(a)

In [4]: my_df.to_csv('my_csv.csv', index=False, header=False)



ANSWER 3

Score 43


import csv
with open(file_path, 'a') as outcsv:   
    #configure writer to write standard csv file
    writer = csv.writer(outcsv, delimiter=',', quotechar='|', quoting=csv.QUOTE_MINIMAL, lineterminator='\n')
    writer.writerow(['number', 'text', 'number'])
    for item in list:
        #Write item to outcsv
        writer.writerow([item[0], item[1], item[2]])

official docs: http://docs.python.org/2/library/csv.html




ANSWER 4

Score 11


If for whatever reason you wanted to do it manually (without using a module like csv,pandas,numpy etc.):

with open('myfile.csv','w') as f:
    for sublist in mylist:
        for item in sublist:
            f.write(item + ',')
        f.write('\n')

Of course, rolling your own version can be error-prone and inefficient ... that's usually why there's a module for that. But sometimes writing your own can help you understand how they work, and sometimes it's just easier.