sTr8_Struggin
sTr8_Struggin

Reputation: 675

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?

Upvotes: 0

Views: 6558

Answers (2)

Ashwini Chaudhary
Ashwini Chaudhary

Reputation: 251021

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)

Upvotes: 3

Gerrat
Gerrat

Reputation: 29710

Well, you can always just manually unpack your data:

data = [[a, b, c, d, e, f, g, h, i, j] for a, [[b,c,d],[e,f,g],[h,i,j]] in data]

...or there are lots of other answers on SO on how to flatten your data (eg. here)

Upvotes: 0

Related Questions