[英]Read the written list of dictionaries from file in Python
我有一個文件,這是一個字典列表:
[{'text': 'this is the text', 'filed1': 'something1', 'filed2': 'something2', 'subtexts': [{'body': 'body of subtext1', 'date': 'xx'}, {'body': 'body of subtext2', 'date': 'yy'}}]
嵌套字典和列表的列表可以包含多個dicts和列表。 我想在python中讀取與此類似的文件,並創建一個數據結構(字典列表)。 如何才能知道它不是json但是它已經通過file.write(str(list))
寫入文件,其中list是我們想要從文件中讀回來的東西?
使用ast.literal_eval
這是一種將Python文字(而不是eval
) eval
為實際數據結構的安全方法。
那是:
import ast
with open('file.txt') as f:
data = ast.literal_eval(f.read())
如果你有超出支持的類型(字符串,字節,數字,元組,列表,dicts,集合,布爾值和None
)的東西,你可以在這個答案中使用我的配方 。
如果json失敗但您知道這是有效的,您可以嘗試:
random_string = "{'a':'1', 'b':'2', 'c':['3', '4']}"
intended_output = eval(random_string)
print intended_output['c'][0]
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.