![](/img/trans.png)
[英]How to read dictionary key:value from json file, search the key in a text file and replace the key value through python?
[英]Read json file to search key value in python
我正在使用python 3.4.3并尝试从文件中读取以下结构
[
{"name": "Afghanistan", "code": "AF"},
{"name": "Ã…land Islands", "code": "AX"},
{"name": "Albania", "code": "AL"}
]
我的代码如下
>>> import json
>>> data = open("c:/iq/data/country.json","r").read()
>>> test = json.load(data)
*Traceback (most recent call last):
File "<pyshell#23>", line 1, in <module>
test = json.load(data)
File "C:\Python34\lib\json\__init__.py", line 265, in load
return loads(fp.read(),
AttributeError: 'str' object has no attribute 'read'*
那我会用类似
for key,value in test.items():
print(key,value)
但是我似乎无法克服上面显示的加载错误。 任何帮助将不胜感激。
您遇到的问题是open().read()
返回一个字符串,但是json.load
需要一个“类似文件的对象”(请参阅文档 。)如果您在这样的字符串中包含文件,则需要json.loads
:
data = open("c:/iq/data/country.json","r").read()
test = json.loads(data)
但是由于要读取文件,因此可以使用json.load
,只需给它一个文件而不是字符串即可:
with open("c:/iq/data/country.json") as data_file:
data = json.load(data_file)
如果需要,可以使用pprint
进行验证:
import json
from pprint import pprint
data_str = open("c:/iq/data/country.json", "r").read()
data = json.loads(data_str)
pprint(data)
with open("c:/iq/data/country.json") as data_file:
data = json.load(data_file)
pprint(data)
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.