Home > Mobile >  How to extract a list of lists from a .txt file in python
How to extract a list of lists from a .txt file in python

Time:11-15

I want to extract a list of lists from a .txt file. The data in the .txt file is given like this: `

[
  [
    [12,34.2,54.1,46.3,12.2],
    [9.2,63,23.7,42.6,15.2]
  ],
  [
    [12,34.2,54.1,46.3,12.2],
    [9.2,63,23.7,42.6,15.2]
  ],
  [
    [12,34.2,54.1,46.3,12.2],
    [9.2,63,23.7,42.6,15.2]
  ]
]

`

I want to store it in a list like:

listA = [[[12,34.2,54.1,46.3,12.2], [9.2,63,23.7,42.6,15.2]], [[12,34.2,54.1,46.3,12.2], [9.2,63,23.7,42.6,15.2]],[[12,34.2,54.1,46.3,12.2], [9.2,63,23.7,42.6,15.2]]]

I tried using the read() function, but it reads as a string, and I can't seem to find out how to extract what I want.

CodePudding user response:

This is how you import a file https://docs.python.org/3/library/fileinput.html

and this is how you parse it https://www.w3schools.com/python/python_json.asp

CodePudding user response:

You can use literal_eval method from ast package to parse string representation of list:

str_list = '''[
  [
    [12,34.2,54.1,46.3,12.2],
    [9.2,63,23.7,42.6,15.2]
  ],
  [
    [12,34.2,54.1,46.3,12.2],
    [9.2,63,23.7,42.6,15.2]
  ],
  [
    [12,34.2,54.1,46.3,12.2],
    [9.2,63,23.7,42.6,15.2]
  ]
]'''

import ast
parsed_list = ast.literal_eval(str_list)
print(parsed_list)

Output:

[[[12, 34.2, 54.1, 46.3, 12.2], [9.2, 63, 23.7, 42.6, 15.2]], [[12, 34.2, 54.1, 46.3, 12.2], [9.2, 63, 23.7, 42.6, 15.2]], [[12, 34.2, 54.1, 46.3, 12.2], [9.2, 63, 23.7, 42.6, 15.2]]]
  • Related