我想閱讀這個 txt 檔案并在 python 中獲取字典串列:
資料.txt:
[{"name": "Aaron", "age": "1"}, {"name": "Bruce", "age": "2"}]
然而:
with open('data.txt','r') as f:
list_of_dict = f.read()
print(list_of_dict[0])
列印--> {"name": "Aaron", "age": "1"}
print(list_of_dict[1])
列印--> {"name": "Bruce", "age": "2"}
print(type(list_of_dict[1])
列印-> dict
print(type(list_of_dict)
列印--> 串列
謝謝
uj5u.com熱心網友回復:
使用json.load(file)代替file.read()
import json
with open("a.txt", encoding="UTF8") as f:
a = json.load(f)
print(type(a)) # <class 'list'>
print(a[0])
print(a[1])
檔案:https ://docs.python.org/3/library/json.html
uj5u.com熱心網友回復:
嘗試使用json模塊:
import json
with open("data.txt", "r") as f_in:
list_of_dict = json.load(f_in)
print(list_of_dict[0])
print(list_of_dict[1])
print(type(list_of_dict[1]))
print(type(list_of_dict))
印刷:
{'name': 'Aaron', 'age': '1'}
{'name': 'Bruce', 'age': '2'}
<class 'dict'>
<class 'list'>
轉載請註明出處,本文鏈接:https://www.uj5u.com/yidong/495558.html
下一篇:用字母和數字在字典串列中排序
