Read a list of lists in txt python 3

3

I have a list of very giant lists and it gets in the way of my code.

So I wanted to save this list into a txt file and ask the algorithm to save this list into a new variable.

Let's assume my list of lists is:

   [[[1],[2]],[[3],[4]]]

If I use:

    text_file = open("lista", "r")
    lista = text_file.read().split(',')

Then my "list" variable returns, for example:

    lista[0] = "[[[1]" 

And in fact I wanted him to understand that list [0] =

    [[1],[2]]

How do I open a file and understand python's internal text structures?

    
asked by anonymous 25.08.2017 / 14:52

1 answer

2

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
    
25.08.2017 / 15:22