Python save arbitrarily nested list to CSV -


i have list composed of strings, integers, , floats, , nested lists of strings, integer, , floats. here example

data = [         1.0,         'one',         [1, 'two'],         [1, 'two', ['three', 4.5]],         ['one', 2, [3.4, ['five', 6]]]     ] 

i want each item of list written line in csv file. so, given above data, file this:

1.0 1 1,two 1,two,three,4.5 one,2,3.4,five,6 

there lots of resources how write list file, have not seen independently of nestedness of list. i'm sure come involving many loops, etc, have more elegant solution?

edit: best thing have come convert each item in list string, remove characters ("[", "]", etc). attach item strings, , write result file:

string = '' in data:     line = str(i).replace("[","")     line = line.replace("]","")     line = line.replace("'","")     line = line.replace(" ","")     string+=line + '\n'  # write string file... 

this feels kludgey, , potentially harmful assumes strings not contain brackets, quotes, or spaces. i'm looking better solution!

what ask more-or-less impossible.

csv flat, tabular storage format. hierarchical nature of "arbitrarily nested lists" not match or fit tabular structure well.

you can flatten nested list each first-level element of nested list appear on single line of output file. isn't csv, strictly speaking. csv readers may correctly read data, others not. and, once flattened in example, can never reconstruct original list reading file.

demonstration:

[1, ["two", "three"], 4.0] 

and

[1, ["two", ["three"]], 4.0] 

both emit:

1 two,three 4.0 

so on reading file, reader/parser won't know of original lists return--the first, two-level list, or second, three-level list. (i can make counter-example arbitrarily complex , ugly.)

in general, nested / hierarchical structures , flat / tabular structures not or compatible.

if want easy storage format arbitrarily nested list, consider json or yaml. provide easy, high-quality storage nested data. e.g.:

import json  outpath = 'out.json' open(outpath, "w") f:     f.write(json.dumps(data)) 

would write data file. read in:

data = json.load(open(out path)) 

but if want csv-ish text:

def flatten(l):     """     flatten nested list.     """     in l:         if isinstance(i, (list, tuple)):             j in flatten(i):                 yield j         else:             yield  def list2csv(l):     """     return csv-ish text nested list.     """     lines = []     row in l:         if isinstance(row, (list, tuple)):             lines.append(",".join(str(i) in flatten(row)))         else:             lines.append(str(row))     return "\n".join(lines)  print list2csv(data) 

yields:

1.0 1 1,two 1,two,three,4.5 one,2,3.4,five,6 

Comments

Popular posts from this blog

java - WARN : org.springframework.web.servlet.PageNotFound - No mapping found for HTTP request with URI [/board/] in DispatcherServlet with name 'appServlet' -

android - How to create dynamically Fragment pager adapter -

1111. appearing after print sequence - php -