【问题标题】:python3 How to read json file, modify and write?python3 如何读取、修改和写入json文件?
【发布时间】:2023-02-18 00:09:27
【问题描述】:

我正在尝试读取一个 json 文件,修改然后保存修改后的版本。 不幸的是,文件的内容没有被保存,而是在原始文件的末尾添加了另一个 json。

我的代码:

with open(os.environ.get("WORKSPACE")+"/test.json", 'r+') as test_file:
    test = json.load(test_file)
    test['COMPONENTS'] = "test components"
    json.dump(test, test_file)

测试.json {"STAGE": "Test", "DATE": "2023-02-17", "TIME": "13:27", "COMPONENTS": ""}

运行代码后 {"STAGE": "Test", "DATE": "2023-02-17", "TIME": "13:27", "COMPONENTS": ""}{"STAGE": "Test", "DATE": "2023-02-17", "TIME": "13:27", "COMPONENTS": "test components"}

预期结果: {"STAGE": "Test", "DATE": "2023-02-17", "TIME": "13:27", "COMPONENTS": "test components"}

请指出我做错了什么

我的环境 蟒蛇 3.10.9 macOS 12.3.1

我尝试使用 w+

Exception has occurred: JSONDecodeError
Expecting value: line 1 column 1 (char 0)
StopIteration: 0

During handling of the above exception, another exception occurred:

  File "/test.py", line 20, in <module>
    test = json.load(test_file)
json.decoder.JSONDecodeError: Expecting value: line 1 column 1 (char 0)

【问题讨论】:

    标签: python json


    【解决方案1】:

    我认为问题是在您的打开模式中添加 +。另请注意,w+ 会截断文件,因此不会读取 JSON。我认为你应该做的是:

    with open(os.environ.get("WORKSPACE")+"/test.json", 'r') as test_file:
        test = json.load(test_file)
        test['COMPONENTS'] = "test components"
    
    with open(os.environ.get("WORKSPACE")+"/test.json", 'w') as test_file:
        json.dump(test, test_file)
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2020-05-13
      • 1970-01-01
      • 2021-04-22
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多