Read a list of lists in txt python 3

Asked

Viewed 1,258 times

3

I have a pretty giant list of lists and it keeps getting in the way of my code.

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

Suppose 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 I really wanted him to understand what list[0] =

    [[1],[2]]

How do I open a file and python understand the internal structure of the text?

1 answer

3


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

  • @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 library pickle supports more complex types than just a list.

Browser other questions tagged

You are not signed in. Login or sign up in order to post.