【发布时间】:2020-03-13 01:09:45
【问题描述】:
我正在为一个学校项目制作一个脚本,该项目要求我收到一个 JSON 文件,该文件告诉我车牌是否在图片中可见。现在,代码将带有图像的 POST 发送到 API,然后返回给我一个 JSON,该 JSON 数据被发送到文件“lastResponse.json”。
给出错误的代码
with open('lastResponse.json', 'r+') as fp:
f = json.dump(r.json(), fp, sort_keys=True, indent=4) # Where the response data is sent to the JSON
data = json.load(f) # Line that triggers the error
print(data["results"]) # Debug code
print("------------------") # Debug code
print(data) # Debug code
# This statement just checks if a license plate is visible
if data["results"]["plate"] is None:
print("No car detected!")
else:
print("Car with plate number '" + data["results"]["plate"] + "' has been detected")
错误
Traceback (most recent call last):
File "DetectionFinished.py", line 19, in <module>
data = json.load(f)
File "/usr/lib/python3.7/json/__init__.py", line 293, in load
return loads(fp.read(),
AttributeError: 'NoneType' object has no attribute 'read'
我在 Python 方面不是很有经验,所以我希望得到解释!
【问题讨论】:
-
您希望
f具有什么价值?它看起来不像 json.dump 返回任何东西。 docs.python.org/3.5/library/json.html#json.dump -
@saffronsnail 我对此进行了测试,如果我这样做了
json.load(fp),则会收到错误JSONDecodeError: Expecting value: line 1 column 1 (char 0)。我也使用它将该数据发送到 JSON 文件。 -
您是否仔细检查过 fp 是否包含您期望的数据?听起来 fp 具有正确的对象类型,但数据错误
-
我把
print(fp)放在with...之后的开头,收到<_io.TextIOWrapper name='lastResponse.json' mode='r+' encoding='UTF-8'>。此外,转储函数正在写入 JSON,因此它可以正确访问fp变量。 -
print(fd.read()) 怎么样?
标签: json python-3.7 attributeerror