1

I'm trying to read a nested list from file but with no success.

The list looks like this:

[14,[["sss","aaa"],"21a"],[[[2,3],"eee"],2423]]

When I read it from file I know that I need to split it, but am not sure which delimiter to use.

If I debug it for list from file and same list which is being assigned to during the compile time:

with open('data.txt', 'r') as f:
      list_file = f.read().split(",[")

list_original = [14,[["sss","aaa"],"21a"],[[[2,3],"eee"],2423]]

I'm getting the following results (debug):

results

martineau
  • 119,623
  • 25
  • 170
  • 301
Igal
  • 4,603
  • 14
  • 41
  • 66

1 Answers1

3

You'll find the json module very useful for this case as follows:

import json

with open('data.txt', encoding='utf-8') as f:
    j = json.load(f)
    print(j)

Output:

[14, [['sss', 'aaa'], '21a'], [[[2, 3], 'eee'], 2423]]
DarkKnight
  • 19,739
  • 3
  • 6
  • 22