如何用Python读写json文件

  • Overview

    The question maybe expressed in english :

    How to update a JOSN file in Python ?

  • About handle

    If you just open a json file, and update the content, you will find that the requested value is not being changed but the entire set of values is being appended to the original file.

    The issue here is that while opening a file and read its contents so the cursor is at the end of the file, by writing to the same file handle, you’re essentially appending to the file.

  • Solutions

  • Easiest way

    The easiest solution would be to close the file after you have read it, then reopen it for writing.

    with open("file.json", "r") as jsonFile:
        data = json.load(jsonFile)
    data['needchange'] = changeContent
    with open("file.json", "w") as jsonFile:
        json.dump(data, jsonFile)
    
  • seek()
  • References

  1. How to update json file with python

猜你喜欢

转载自blog.csdn.net/The_Time_Runner/article/details/115023771