How to write nested lists to a CSV

Viewed 51

I currently have a python program which outputs into a single list composed of many smaller lists of length 3. So, the output currently looks like

[[0.01, 0.0124, 4.3201], [0.015, 0.0192, 5.1098], ... , [0.105, 0.0379, 3.7899]]

The nth terms in each array represent the three variables over different steps. I would like to export this data to a csv where it is columnated like

0.01    0.0124    4.3201
0.015   0.0192    5.1098
...
0.105   0.0379    3.7899

What is the simplest way of going about this?

3 Answers

Try this:

data=[[0.01, 0.0124, 4.3201], [0.015, 0.0192, 5.1098] , [0.105, 0.0379, 3.7899]]
wtr = csv.writer(open ('out.csv', 'w'), delimiter=',', lineterminator='\n')
for x in data : wtr.writerow (x)

You can use the csv module

def write_data( filename, data ):
    with open(filename,"w") as ff:
        writer = csv.writer(ff,delimiter="\t")
        for row in data:
            writer.writerow(row)

Convert the nested list to pandas and save as excel

 import pandas as pd

nested_ls=[[0.01, 0.0124, 4.3201], [0.015, 0.0192, 5.1098] , [0.105, 0.0379, 3.7899]]
df=pd.DataFrame(nested_ls,columns=['c1','c2','c3'])
df.to_excel('opt.xlsx')
Related