版权声明:风火编程, 欢迎指正. https://blog.csdn.net/weixin_42620314/article/details/85318730
更新或更改json文件
如果文件不存在, 执行以下逻辑:**
-
通过"r+"方式打开文件,
-
清空文件对象,
-
再把指针移动到开头,
-
写入新数据
-
清空文件对象,
-
把指针移动到开头,
-
写入新数据
示例代码import os
import jsond = { "111": "111", "222": "222" } j = json.dumps(d) if not os.path.exists("1111111111.txt"): with open("1111111111.txt", "w", encoding="utf-8") as f: f.write(j) else: with open("1111111111.txt", "r+", encoding="utf-8") as f: data = json.loads(f.read(), strict=False) print(data) f.truncate() f.seek(0, 0) data["777"] = 777 f.write(json.dumps(data))