Ask Your Question
0

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

asked 2016-04-21 22:44:32 -0500

k1monfared gravatar image

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')
out.write(str(L))
out.close()

And then

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

to only get

'[ [ [1,2], [1,2] ], [ [1,2,3], [1,3], [1,2,3] ], 1 ]'
edit retag flag offensive close merge delete

1 answer

Sort by ยป oldest newest most voted
1

answered 2016-04-22 07:27:07 -0500

calc314 gravatar image

a. Try a csv file. You can read and write as follows

writing:

with open('yourfile.csv', 'w') as f1:
writefile = csv.writer(f1)
writefile.writerows(data_list)

reading:

import csv
with open('your file.csv','rU') as f1:
    data=list( csv.reader(f1) )

b. saving a more complex data format

Try using save and load.

save(data,'myfile')

result=load('myfile')
edit flag offensive delete link more

Comments

Thank you very much. Your answer for part b was exactly what I was looking for. Thanks. Still out of curiosity, for a. I get a list that looks like [['1','2'],['3','4']]. Any suggestions on how to avoid going through the whole list and turning strings into numbers?

k1monfared gravatar imagek1monfared ( 2016-04-22 11:11:03 -0500 )edit

LL = [['1','2'],['3','4']]

 [map(int,L) for L in LL]
ndomes gravatar imagendomes ( 2016-04-23 15:05:42 -0500 )edit

Your Answer

Please start posting anonymously - your entry will be published after you log in or create a new account.

Add Answer

Question Tools

1 follower

Stats

Asked: 2016-04-21 22:44:32 -0500

Seen: 167 times

Last updated: Apr 22 '16