Read the written list of dictionaries from file in Python

前端 未结 2 1652
逝去的感伤
逝去的感伤 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:29

    If json has failed but you know that this is valid, you could try:

    random_string = "{'a':'1', 'b':'2', 'c':['3', '4']}"
    intended_output = eval(random_string)
    
    print intended_output['c'][0]
    
    0 讨论(0)
  • 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.

    0 讨论(0)
提交回复
热议问题