【发布时间】:2017-01-14 20:35:05
【问题描述】:
我不精通 json 或 python。我正在创建一个简单的脚本来获取本地当前温度并将其放入 txt 文件中(因为我假设我可以让 python 在稍后的步骤中读取 txt 文件)。到目前为止,我已经设法使用 json 数据创建了 txt 文件,但我只想将我想要的相关数据写入 txt 文件。
import requests
import json
key = [KEY]
while 1:
res = requests.get('http://api.wunderground.com/api/' + key + '/geolookup/conditions/q/[STATE]/[ZIP].json')
json_string = res.json()
with open("weather_result.txt","w") as fp:
json.dumps(json_string, fp)
temperature_string = parsed_json['current_observation']['temp_f']
print (temperature_string)
我哪里错了?我似乎无法理解这个 json 转储的字符串或字典。
感谢您的帮助。
【问题讨论】:
-
我看不懂你的代码。
while 1?parsed_json定义在哪里? -
你熟悉
fp.write('string here')吗? -
您还没有告诉我们出了什么问题或文件中的内容。看起来您有一个无限循环,只是一遍又一遍地执行请求。文本文件是否应该是
parsed_json['current_observation']['temp_f']中内容的 json 转储。你叫它temperture_string...它只是一个字符串吗?您真的要编写字符串的 json 序列化还是只编写字符串?是否要多次写入此数据(然后以换行符终止,以便将它们区分开来)? -
在阅读了这些 cmets 之后,我意识到我的错误,“parsed_json”没有被定义,因为我打算使用“json_string”。那个和“while 1:”都是我没有意识到的旧代码的残余。我想做的就是获取当前温度。我从使用 json 开始,因为我正在学习一个教程,然后继续前进。