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
Python's built-in CSV module can handle this easily:
import csv
with open("output.csv", "wb") 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()
as documented in the library reference page linked above.
Update for Python 3
import csv
with open("out.csv", "w", newline="") as f:
writer = csv.writer(f)
writer.writerows(a)
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)
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
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:
import pandas
yourlist = [[...],...,[...]]
pd = pandas.DataFrame(yourlist)
pd.to_csv("mylist.csv")
The good part you can change somethings to make a better csv file:
yourlist = [[...],...,[...]]
columns = ["abcd","bcde","cdef"] #a csv with 3 columns
index = [i[0] for i in yourlist] #first element of every list in yourlist
not_index_list = [i[1:] for i in yourlist]
pd = pandas.DataFrame(not_index_list, columns = columns, index = index)
#Now you have a csv with columns and index:
pd.to_csv("mylist.csv")