Python代码打开json文件-更优化
我怎样才能把这段代码写得更优化,而不是重复呢?所以,首先我检查是否有 .json 文件,如果没有,我就创建它。如果有,我首先打开它,用新数据更新它,然后再次写入。
if not os.path.exists(json_path):
with open(json_path, "w") as json_file:
json.dump(my_dict, json_file)
else:
with open(json_path) as json_file:
data = json.load(json_file)
data.update(my_dict)
with open(json_path, 'w') as json__file:
json.dump(data, json__file)
How could I write this piece of code more optimal, not to have repetition? So, first I'm checking if there's a .json file, if there isn't I make it. If there is, I first open it, update it with new data, and then write in it again.
if not os.path.exists(json_path):
with open(json_path, "w") as json_file:
json.dump(my_dict, json_file)
else:
with open(json_path) as json_file:
data = json.load(json_file)
data.update(my_dict)
with open(json_path, 'w') as json__file:
json.dump(data, json__file)
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
我认为你可以反转你的条件来先读取文件。然后稍后写入文件,因为你总是最终会写入。
I think you can invert your condition to read the file first. Then later write to the file because you always end up writing.