0

I trying to write complex nested list into file as it is,

so this is my list format

list=[[x number of elements],'a','b','c'],[y number of elements],'d',e',f']]

I am trying to write this in file as it is

[[x number of elements],'a','b','c'],[y number of elements],'d',e',f']]

So please help me out!

StackPointer
  • 519
  • 2
  • 7
  • 16
  • Try this http://stackoverflow.com/questions/899103/python-write-a-list-to-a-file – Tanveer Alam Nov 15 '14 at 22:47
  • What have you tried until now? Since you want to write as is, `open('file.txt', 'w').write(mylist) should work. Also don't use `list` as the name of your list since it is a reserved name in python. – vikramls Nov 15 '14 at 22:53
  • @vikramls no it woudn't work! And of course here I have written list just for making it understandable that it is a list. Its not a name of the list. – StackPointer Nov 15 '14 at 23:04
  • I meant to write `str(mylist)` – vikramls Nov 15 '14 at 23:18
  • You might get more useful answers if you also mention the reason you are trying to do this and some of what your actual code looks like. – Stuart Nov 15 '14 at 23:38

2 Answers2

2

If you want to ensure the list can be read again, and you're sure it only contains simple Python types (lists, dictionaries, strings, and numbers), then you can do something like this:

import json
with open('output.txt', 'w') as out_file:
    json.dump(your_list, out_file)

To pull it back into Python, you can do this:

import json
with open('output.txt', 'r') as in_file:
    your_list = json.load(in_file)
Kevin
  • 25,251
  • 7
  • 54
  • 78
0

Ignoring that your list is not correct one, you can do this with:

s = [[[1, 3, 4],'a','b','c'],[4, 5],'d','e','f']
text_file = open("Output.txt", "w")
text_file.write(str(s))
text_file.close()

Thus simply converting the list to a string and saving it.

Salvador Dali
  • 182,715
  • 129
  • 638
  • 708