-1

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.

Oghli
  • 2,200
  • 1
  • 15
  • 37

2 Answers2

0

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

Jatel
  • 40
  • 8
0

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]]]
Oghli
  • 2,200
  • 1
  • 15
  • 37