![](/img/trans.png)
[英]Reading/writing a list of nested dictionaries to/from a CSV file (Python)
[英]Reading a list from a file, and converting it into a list of Python dictionaries
假設我是從一個名為“ info.dat”的文件中讀取的,其中包含以下內容:
[{'name': 'Bob', 'occupation': 'architect', 'car': 'volvo'}, {'name': 'Steve', 'occupation': 'builder', 'car': 'Ford'}]
我該如何閱讀並將其變成詞典列表? 如果我這樣做:
with open('info.dat') as f:
data = f.read()
它只是將其讀取為單個字符串,即使我這樣做也是為了分解它:
data = data[1:-1]
data = data.split('},')
我仍然必須將其放入字典中。 有沒有更好/更干凈的方法可以做到這一點?
使用ast.literal_eval
:
import ast
with open('info.dat') as f:
data = ast.literal_eval(f.read())
正如文檔中所述,這比文檔“安全地評估表達式節點或包含Python表達式的字符串”要安全得多。
如果不安全,將引發錯誤。
使用ast.literal_eval
可以讀取簡單的Python文字,例如dicts / tuples / ast.literal_eval
盡管不像eval
那樣“強大”,但由於其限制性更強,因此更安全。
from ast import literal_eval
with open('yourfile') as fin:
your_list = literal_eval(fin.read())
也許使用eval-
eval("ld ="+open("info.dat").read())
然后使用ld
變量訪問列表
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.