Read the written list of dictionaries from file in Python

前端 未结 2 1651
逝去的感伤
逝去的感伤 2021-01-03 07:07

I have a file which is a list of dictionaries in this way:

[{\'text\': \'this is the text\', \'filed1\': \'something1\', \'filed2\': \'something2\', \'subtexts

2条回答
  •  南笙
    南笙 (楼主)
    2021-01-03 07:34

    Use ast.literal_eval which is a safe way of evaluating Python literals (as opposed to eval) into actual data structures.

    That is:

    import ast
    
    with open('file.txt') as f:
        data = ast.literal_eval(f.read())
    

    If you have something beyond the supported types (strings, bytes, numbers, tuples, lists, dicts, sets, booleans, and None), you can use my recipe in this answer.

提交回复
热议问题