-2

This seems pretty straightforward, but I can't find any alternative solutions online. I have a text file like so:

[[[0, 0, 'no'], [3, 0, 1]], [[4, 4, 'coming']]]
[[[0, 0, 'yes'], [2, 0, 2], [2, 2, '15-19']], [[9, 4, 'not coming']]]

How do I go about parsing this file in such a way where it'd follow the same logic:

# Read in file
# Work with the first line, or list, of lists 
    # Do this by putting it into a temporary list of lists variable 

Is what I'm asking possible? I'm just wanting to save myself time working with a monstrous text file that'd be way easier this way.

bmcisme
  • 15
  • 6

1 Answers1

1

You can use ast.literal_eval to parser the file:

from pprint import pprint
from ast import literal_eval

data = []
with open('<your file.txt>', 'r') as f_in:
    for line in f_in:
        data.extend(literal_eval('[' + line + ']'))

pprint(data)

Prints:

[[[[0, 0, 'no'], [3, 0, 1]], [[4, 4, 'coming']]],
 [[[0, 0, 'yes'], [2, 0, 2], [2, 2, '15-19']], [[9, 4, 'not coming']]]]
Andrej Kesely
  • 81,807
  • 10
  • 31
  • 56