It’s up to you serialize your object before saving it to file. In Python, there is the native library pickle
that you can use:
Saving the object in file
To save the object in file, just use the function dump
. Just indicate the object you want to save and the stream representing the archive:
import pickle
lista = [[[1],[2]],[[3],[4]]]
with open("data.txt", "wb") as file:
pickle.dump(lista, file)
Thus the object lista
will be saved in the archive data.txt
. Note that the file must be opened for binary writing (wb
). The contents of the file for this example will be:
\x80\x03]q\x00(]q\x01(]q\x02K\x01a]q\x03K\x02ae]q\x04(]q\x05K\x03a]q\x06K\x04aee.
That it’s nothing more than the representation of the object.
Recovering Data from File
To recover the file object, just use the function load
. Just indicate the stream of the file you want to get the data as parameter:
with open("data.txt", "rb") as file:
lista2 = pickle.load(file)
Thus, lista2
will be a list of lists, as well as lista
initially. We can check by accessing the position 0 of the same:
print(lista2[0]) # -> [[1], [2]]
Or even check whether lista2
is equal to lista
:
print(lista == lista2) # -> True
I responded by suggesting the use of
eval()
but did not know the size of the problem, very good answer! + 1– Mathiasfc
@Mathiasfalci is, hard to say with accuracy, but there is always a way preferable to
eval
. In this particular case it might not be so critical, but it would be good to avoid. Apart from the fact that the librarypickle
supports more complex types than just a list.– Woss