Search code examples
pythonlisttext

How to read a list in a text file in python


I have this list

l1=[[[0,1,2,3,4],[5,6,7]],[8,9,10],[11,12,13,14]]

and I save this list in a text file

with open('l1.txt', 'w') as f1:
      f1.write(str(l1))

Now I have a text file with the list. How can I read this list in python? I tried with

list1= open("l1.txt", "r")
list2= list1.read()
l1= list2.strip('][').split(', ')

With this I have

l1=['0','1','2','3','4','5','6','7','8','9','10','11','12','13','14']

but this isn't the list I have at the beginning


Solution

  • As @Cardstdani mentioned, you can try to use eval. However, I suggest avoiding eval in all but the rarest of cases.

    I would suggest serialising and deserialising it in some nice, way, such as using JSON:

    Save:

    import json
    
    l1=[[[0,1,2,3,4],[5,6,7]],[8,9,10],[11,12,13,14]]
    
    with open("l1.json", "w") as f:
        json.dump(l1, f)
    

    Load:

    import json
    
    with open("l1.json") as f:
        l1 = json.load(f)