I printed a list l
to a file using
f = open('a.txt', 'a')
f.write(str(l))
Now, How can I retrieve the list from the file.
And the list l
is a list of list of dictionaries.
I printed a list l
to a file using
f = open('a.txt', 'a')
f.write(str(l))
Now, How can I retrieve the list from the file.
And the list l
is a list of list of dictionaries.
Another way is to serialize into Json and write to file.
import json
ll = [ { 'akey1':'val1', 'akey2':'val2'}, {'bkey1':'bkey1', 'bkey2':'bkey2'}]
# write to file
with open('backup.json', 'w') as fout:
fout.write(json.dumps(ll))
# read from file
with open('backup.json', 'r') as fin:
ll_in = json.load(fin)
print ll_in
Its not the best way to serialize data to a file, but to do the conversion back from string to list you could use ast.literal_eval
.
e.g.
import ast
l = [['dir/path', 'other/path'],['path/path', 'blah/xyz']]
with open('a.txt', 'a') as f:
f.write(str(l))
with open('a.txt') as fread:
s = fread.read()
l2 = ast.literal_eval(s)
print type(l2)
for i in l2:
print i
There are plenty of better ways, pickle or json standout as good choices.
Note that as you append a complete list to your file each time, repeated runs of your code to write to the file will result in the file containing invalid python syntax that cannot be eval
led back to a list.
I think the best way if to use Pickles
you can use it that way :
def createPickleFile(self):
listToStore = self.traceManager.getData()
fileObject = open("mypath", 'wb')
pickle.dump(listToStore, fileObject)
fileObject.close()
def getPickle(self):
tesst = OrderedDict()
fileObject = open(CONST_DEBUG_FILE_PATH, 'rb')
pickleDict = pickle.load(fileObject)
for item in pickleDict:
print(item,pickleDict[item])
self.traceManager.addValue(item,pickleDict[item])
fileObject.close()
return pickleDict
Use ast:
import ast
f = open('a.txt').read()
l = ast.literal_eval(s)
The l
will be a list object.
This is one way to do it:
f = open('yourfile.txt').read()