风火编程--更新json文件

版权声明:风火编程, 欢迎指正. https://blog.csdn.net/weixin_42620314/article/details/85318730

更新或更改json文件

如果文件不存在, 执行以下逻辑:**

  1. 通过"r+"方式打开文件,

  2. 清空文件对象,

  3. 再把指针移动到开头,

  4. 写入新数据

  5. 清空文件对象,

  6. 把指针移动到开头,

  7. 写入新数据
    示例代码

    import os
    import json

     d = {
     "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))
    

猜你喜欢

转载自blog.csdn.net/weixin_42620314/article/details/85318730