Reputation: 35
I have a file where each line is a list representation of a tree. For example, one of these lines in the file is:
[1, [[2,[]], [3, [ [5,[]], [6, [ [10,[]] ] ] ]], [4, [ [7,[]], [8,[]], [9,[]] ]] ]]
If I copy and paste this into my program, it understands that it is a list and I can easily manipulate it to find the root and the children, and then take those children and find their children, etc. When I read a file line by line, it takes those lines and turns them into strings. If I try to convert these strings into lists then it takes each individual character in the string to be a different item in the list and thats not what I want.
I just want to know how I can read a file line by line but instead of it spitting out strings, it gives me each line in its literal list form. The file I'm reading is a .txt file and it must stay this way I cant save it as a .py file or anything like that.
Upvotes: 2
Views: 163
Reputation: 2640
You can load a datafile into a list like this and the types will be handled correctly:
def load_lines():
res=[]
with open("datafile.txt","r+") as f:
for line in f.readlines():
a_line = [ast.literal_eval(text) for text in line.split(',')]
res.append(a_line)
return res
Upvotes: 0
Reputation: 5670
Try the ast
module:
>>> s = "[1, [[2,[]], [3, [ [5,[]], [6, [ [10,[]] ] ] ]], [4, [ [7,[]], [8,[]], [9,[]] ]] ]]"
>>> l = ast.literal_eval(s)
>>> l[0]
1
Upvotes: 2