如何从文件中读取嵌套列表?

How to read a nested list from a file?

我正在尝试从文件中读取嵌套列表,但没有成功。

列表如下所示:

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

当我从文件中读取它时,我知道我需要拆分它,但不确定要使用哪个分隔符。

如果我从文件和在编译期间分配给的相同列表中调试它:

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

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

我得到以下结果(调试):

您会发现 json 模块对于这种情况非常有用,如下所示:

import json

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

输出:

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