Search code examples
pythoncsvtuplesnested-lists

How to write a complex nested list to a csv file without brackets in python?


So I am having trouble writing my data to a .csv file using the import csv package. My data is stored in the following general format:

[(Time, [[ID#, MAG, Merr], [ID#, MAG, Merr]])]

An example of my data set is shown below:

data = [(24.23, [[1.0, 18.116, 0.062], [2.0, 18.236, 0.063], [3.0, 17.855, 0.063]]),
       (25.67, [[1.0, 17.968, 0.044], [2.0, 18.189, 0.051], [3.0, 17.757, 0.048]]),
       (26.89, [[1.0, 17.634, 0.025], [2.0, 17.781, 0.029], [3.0, 17.454, 0.026]])]

I wanted to write this data into a .csv file that would look like this:

24.23,  1.0,  18.116,  0.062,  2.0,  18.236,  0.063,  3.0,  17.855,  0.063
25.67,  1.0,  17.968,  0.044,  2.0,  18.189,  0.051,  3.0,  17.757,  0.048
28.89,  1.0,  17.634,  0.025,  2.0,  17.781,  0.029,  3.0,  17.454,  0.026

I tried the following:

import csv
with open('myfile.csv', 'w') as f:
        w = csv.writer(f, dialect = 'excel-tab')
        w.writerows(data)

But I got tons of brackets in the results. I was wondering if there was a better way to approach this?


Solution

  • You should flatten the the list first before writing it to csv file.

    with open('myfile.csv', 'w') as f:
            w = csv.writer(f, dialect='excel-tab') # use `delimiter=','` for ',' in file
            for item in data:
                lst = [item[0]] + [y for x in item[1] for y in x]
                w.writerow(lst)