I have a list that is composed of strings, integers, and floats, and nested lists of strings, integer, and floats. Here is an example
data = [
1.0,
'One',
[1, 'Two'],
[1, 'Two', ['Three', 4.5]],
['One', 2, [3.4, ['Five', 6]]]
]
I want each item of the list written to a line in a CSV file. So, given the above data, the file would look like this:
1.0
One
1,Two
1,Two,Three,4.5
One,2,3.4,Five,6
There are lots of resources about how to write a list to a file, but i have not seen any that do so independently of the nestedness of the list. I'm sure i could come up with something involving many loops, etc, but does anyone have a more elegant solution?
EDIT: The best thing i have come up with is to convert each item in the list to a string, then remove the extra characters ("[", "]", etc). Then you attach the item strings, and write the result to a file:
string = ''
for i in data:
line = str(i).replace("[","")
line = line.replace("]","")
line = line.replace("'","")
line = line.replace(" ","")
string+=line + '\n'
# write string to file...
This just feels kludgey, and it is potentially harmful as it assumes the strings do not contain the brackets, quotes, or spaces. I'm looking for a better solution!