Just serialize your object before saving it to file. In Python, there's the native % _content library you can use:
Saving the object to a file
To save the object to a file, you only have to use the pickle
function. Simply indicate the object you want to save and the stream that represents the file:
import pickle
lista = [[[1],[2]],[[3],[4]]]
with open("data.txt", "wb") as file:
pickle.dump(lista, file)
In this way the dump
object will be saved in the lista
file. Note that the file must be opened for binary writing (% with%). 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 is nothing more than the representation of the object.
Retrieving the file data
To retrieve the object from the file, simply use the data.txt
function. Just indicate the stream of the file you want to get the data as a parameter:
with open("data.txt", "rb") as file:
lista2 = pickle.load(file)
Thus,% w / w% will be a list of lists, as well as% w / w of% initially. We can check by accessing position 0 of it:
print(lista2[0]) # -> [[1], [2]]
Or even check that wb
is equal to load
:
print(lista == lista2) # -> True