Python如何更新JSON-fi

2024-09-30 20:24:33 发布

您现在位置:Python中文网/ 问答频道 /正文

我有一个JSON文件,它看起来像:

{
    "files": [
        {
            "nameandpath": "/home/test/File1.zip",
            "MD5": "e226664e39dc82749d05d07d6c3078b9",
            "name": "File1"
        },
        {
            "nameandpath": "/home/test/File2.zip",
            "MD5": "dbb11b2095c952ff1d4b284523d3085f",
            "name": "File2"
        }
    ]
}

当条件为真时,我只想更新两行nameandpath和MD5。 条件是,如果被测试的文件存在于JSON文件中:我将更新该行,否则我将用它的3个值添加该文件。在

^{pr2}$

我无法更新现有线路 我无法测试添加新行。在

你能帮帮我吗?
我怎么能做这种事?在

目前我的代码:

# getting file name
# getting MD5 of the file

jsonfile = "/home/test/filesliste.json"

 with open(jasonfile, "r+") as json_file:
        data = json.load(json_file)
        for tp in data['files']:
            if tp['name'] == name:
                if tp['MD5'] == fileMD5:
                    print("same MD5")
                    # adding this file to json file
                else:
                    print("NOT THE same MD5")
                    # updating the file info into json file

Tags: 文件nametestjsonhomefileszip条件
1条回答
网友
1楼 · 发布于 2024-09-30 20:24:33

我不清楚你到底在挣扎什么。下面是我如何组织代码,也许这有助于:

jsonfile = "/home/test/filesliste.json"

# read json file
with open(jsonfile) as f:
    data = json.load(f)

# find index of file or -1 if not found
index = -1
for i, tp in enumerate(data['files']):
    if tp['name'] == name and tp['MD5'] == fileMD5:
        index = i
        break

# update data
# we're lazy and just delete the old file info, then re-add it
if index >= 0:
    del data['files'][index]

tp = {
    "name": ...,
    "nameandpath": ...,
    "MD5": ...,
}
data.append(tp)

# write data back to file
with open(jsonfile) as f:
    # json.dump or something like that

MD5型

MD5不应再使用,因为它被认为是损坏的。如果可能的话,您应该用SHA-2或SHA-3来替换它,它们类似但更安全。在

相关问题 更多 >