Ask Your Question

Revision history [back]

click to hide/show revision 1
initial version

What's a common way to save and load a list?

I have calculated a list through a long calculation to do some other calculations with it. So I saved the list in a .txt file and in the file it looks like this:

[[[-1/10, 1.02421477975960],
  [-99/1000, 1.02369404664481],
  [-49/500, 1.02317986236459],
  [-97/1000, 1.02267219319285], 

Now that I want to load it again, I realized that I have to strip the \n's and then get rid of the brackets and extra commas etc. While I still have to do this for the current file, I want to know what are the common ways to save a list (and other similar python objects) so that I don't have to do all of this again? In other words:

a. How can I save the each element of a list in a line of a file? That is, to get something like:

-1/10, 1.02421477975960
-99/1000, 1.02369404664481
-49/500, 1.02317986236459
-97/1000, 1.02267219319285

b. How can I save a list (higher dimensional array) into a file and then read it. I tried the following but I seem to be unable to read it:

L = [ [ [1,2], [1,2] ], [ [1,2,3], [1,3], [1,2,3] ], 1 ]
out = file('out','w')

And then

L = open('out','r')

to only get

'[ [ [1,2], [1,2] ], [ [1,2,3], [1,3], [1,2,3] ], 1 ]'