I have a list of 16 elements, and each element is another 500 elements long. I would like to write this to a txt file so I no longer have to create the list from a simulation. How can I do this, and then access the list again?
Pickle will work, but the shortcoming is that it is a Python-specific binary format. Save as JSON for easy reading and re-use in other applications:
import json
LoL = [ range(5), list("ABCDE"), range(5) ]
with open('Jfile.txt','w') as myfile:
json.dump(LoL,myfile)
The file now contains:
[[0, 1, 2, 3, 4], ["A", "B", "C", "D", "E"], [0, 1, 2, 3, 4]]
To get it back later:
with open('Jfile.txt','r') as infile:
newList = json.load(infile)
print newList
To store it:
import cPickle
savefilePath = 'path/to/file'
with open(savefilePath, 'w') as savefile:
cPickle.dump(myBigList, savefile)
To get it back:
import cPickle
savefilePath = 'path/to/file'
with open(savefilePath) as savefile:
myBigList = cPickle.load(savefile)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With