Search code examples
pythonpython-3.xtree

How to read lines of a file to be lists instead of strings in python


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.


Solution

  • Try the ast module:

    >>> s = "[1, [[2,[]], [3, [ [5,[]], [6, [ [10,[]] ] ] ]], [4, [ [7,[]], [8,[]], [9,[]] ]] ]]"
    >>> l = ast.literal_eval(s)
    >>> l[0]
    1