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
Python's built-in CSV module can handle this easily:
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 tocsv.writer()
as documented in the library reference page linked above.Ambers's solution also works well for numpy arrays:
official docs: http://docs.python.org/2/library/csv.html
Make sure to indicate
lineterinator='\n'
when create the writer; otherwise, an extra empty line might be written into file after each data line when data sources are from other csv file...Here is my solution:
You could use
pandas
:Using csv.writer in my very large list took quite a time. I decided to use pandas, it was faster and more easy to control and understand:
The good part you can change somethings to make a better csv file: