擅长:python、mysql、java
<p>您不想指定“rb”,因为JSON模块无法读取文件的二进制表示。你可能想要“utf-8”编码和“read”。编辑:我最初说过这两个都是默认值,但我注意到许多操作系统的默认编码不同,Python在open()中使用系统设置作为默认值。因此,我建议显式地将编码设置提供为“utf-8”。</p>
<p>json支持使用“json.load”而不是“json.loads”从打开的文件中加载,后者从字符串中加载,因此我们可以跳过作为文本的读入,直接转到json。我认为您不想“加载”单独的行,因为这可能不是有效的JSON。</p>
<pre><code>import json
# open has __enter__ and __exit__ functions, so we can call it as a guard
# using "with" syntax and it'll close when the scope ends
with open(r".\myjson.json", encoding="utf-8") as fh:
# load() is a convenience function to help us avoid iterating lines
# on our own. It calls loads() on the whole doc and returns an obj
json_obj = json.load(fh)
print (json_obj)
</code></pre>