oriana zhou
oriana zhou

Reputation: 13

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

Upvotes: 0

Views: 619

Answers (4)

Daweo
Daweo

Reputation: 36330

You might use ast.literal_eval, it is safer than eval (see docs), in this case

import ast
x = [[1,2,3],[4,5],[6]] # original list
s = str(x) # string representation
x2 = ast.literal_eval(s) # list built from representation
print(x == x2) # True

Note: for brevity I do not include writing/reading to files, which can be done as for any normal text file

Upvotes: 1

Peter
Peter

Reputation: 3495

Serialization is the way to go for what you're wanting to do. There are different libraries for this, but json would be ideal in this case since you're not using any custom classes.

import json

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

with open('l1.txt', 'w') as f1:
    json.dump(l1, f1)

with open('l1.txt', 'w') as f2:
    l2 = json.load(f2)

print(l1 == l2)
# True

As a side note for the other answer, while eval would work, it's extremely unsafe (someone could easily write malicious code in your text file), and I'd recommend you to forget about it until you become a lot more proficient at coding.

Upvotes: 1

tituszban
tituszban

Reputation: 5152

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)

Upvotes: 3

Cardstdani
Cardstdani

Reputation: 5223

You need to use eval() function to read explicitly from a text file and then convert to a valid Python multi-dimensional list:

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

#In your case
list1= open("l1.txt", "r")
list2= list1.read()
l1= eval(list2)

Output:*

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

Upvotes: 0

Related Questions