【发布时间】:2017-07-18 14:05:33
【问题描述】:
我想创建一个文件,将多个关于沿海天气条件(潮汐、风等)的 python 字典组合在一起,可以每天更新。数据来自多个 API 和网站,我将每个 API 和网站都转换为 Python 字典,并使用以下代码行合并到单个字典中:
OneDayWeather_data = {'Willydata' : Willydata, 'Bureau of Meteorology' : BoMdata, 'WeatherZone' : WZdata}
我的目标是每天对网站进行抽样;并使用网站上每天的天气和预报更新单个文件。我认为最好的方法是使用日期为层次结构创建一个新的顶层。所以它会像这样:
Weather_data['18/07/2017']['Willy']['Winds']
Weather_data['18/07/2017']['BoMdata']['Winds']
对于每一天,我都会为新一天的数据添加一个新的顶级条目,即
AllWeatherData['19/07/2017']['Willy']['Winds']
我已经尝试过使用堆栈溢出建议的各种方法(完全披露:我对 Python 很陌生)。例如,
# write the initial file
with open('test.json', 'w') as f:
json.dump(OneDayWeather_data, f)
# open the initial file and attempt to append
with open('test.json','r+') as f:
dic = dict(json.load(f))
dic.update(OneDayWeather_data)
json.dump(dic, f)
# reopen the appended file
with open('test.json', 'r') as f2:
json_object = json.load(f2)
...但是当我尝试重新打开时,我不断收到错误(在这种情况下:ValueError(errmsg("Extra data", s, end, len(s))))。希望有一些专业知识的人可以权衡如何解决这个问题。
谢谢!
【问题讨论】:
-
使用 TinyDB 怎么样? tinydb.readthedocs.io/en/latest
标签: python json dictionary