2017-07-18 22 views
0

我想创建一个单独的文件,将多个可以每天更新的有关沿海天气条件(潮汐,风力等)的python字典组合起来。该数据来自多个API和网站,每一个我用下面的代码行转换为Python字典,并合并成一个单一的词典:将多个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( “额外数据”,S端,LEN(S)))当我尝试重新打开)。希望有一些专业知识的人可以权衡如何解决这个问题。

谢谢!

+0

使用TinyDB怎么样? http://tinydb.readthedocs.io/en/latest/ – Grimmy

回答

0

你实际上是追加更新字典现有的字典

# write the initial file 
import json 

OneDayWeather_data = {'a':'b'} 

with open('test.json', 'w') as f: 
    json.dump(OneDayWeather_data, f) 

OneDayWeather_data = {'c':'d'} 

# 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) 

在这个阶段,你的test.json看起来像

{"a": "b"}{"a": "b", "c": "d"} 

您可以分开读取/更新/写

with open('test.json','r') as f: 
    dic = dict(json.load(f)) 
    dic.update(OneDayWeather_data) 
with open('test.json', 'w') as f: 
    json.dump(dic, f) 

同样的答案也可以在How to append in a json file in Python?

+0

谢谢!完美工作。 –