在 Python 中读取旧版本的 JSON 文件

问题描述 投票:0回答:1

我正在尝试从不同的文件夹读取 json 文件,但其中的值是该文件的旧版本。但是,同一文件夹中的不同 json 可以正确读取。 如果我将 apply.json 复制到我的 pwd 中,那么在这种情况下它可以正常工作。 例如-

'''In the json:
   AmountMax : 0
When read in python:
   AmountMax : 90'''

with open("../frontend/src/components/Presets/apply.json") as infile:
    settings_data = json.load(infile)
    print(settings_data)

我完全不知道这是如何或为什么发生的,任何建议或帮助将非常感谢。我尝试确保路径正确,甚至重新创建了文件。

编辑: 输出如下

apply.json -
{
  "Active": "Preset 0",
  "reqAmountMin": 0,
  "reqAmountMax": 0
}

Python Output reading apply.json from orignal folder -
{'reqAmountMin': 0, 'reqAmountMax': 90}

Python Output reading apply.json copied to pwd -
{'Active': 'Preset 0', 'reqAmountMin': 0, 'reqAmountMax': 0}
python json file mismatch
1个回答
0
投票

检查工作目录

import os
print("Current Working Directory:", os.getcwd())

如果脚本与 JSON 文件不在同一目录中(您的情况),您可能需要相应地调整相对路径。

import json

file_path = "/absolute/path/apply.json"

with open(file_path) as infile:
    settings_data = json.load(infile)
    print(settings_data)

更换 “/绝对/路径/apply.json” 与文件的实际绝对路径。

© www.soinside.com 2019 - 2024. All rights reserved.