将字典写入txt文件,并以字典形式读取出来。
以ID为唯一键值,相同的ID会被覆盖
import os
import json
curdir = os.path.dirname(os.path.realpath(__file__))
path = os.path.join(curdir,'test.txt')
data = {"ID": "92",
"a":"123",
"b":"234"}
def write(path):
if not os.path.exists(path):
json_data = {}
else:
json_data = read(path)
with open(path,'w') as f:
json_data[data['ID']] = data
json.dump(json_data,f)
def read(path):
len = os.path.getsize(path)
if len:
with open(path,'r') as f:
return json.load(f)
write(path)
print read(path)