首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >Python如何更新JSON文件

Python如何更新JSON文件
EN

Stack Overflow用户
提问于 2017-01-19 01:00:24
回答 1查看 1.8K关注 0票数 0

我有一个JSON文件,如下所示:

代码语言:javascript
复制
{
    "files": [
        {
            "nameandpath": "/home/test/File1.zip",
            "MD5": "e226664e39dc82749d05d07d6c3078b9",
            "name": "File1"
        },
        {
            "nameandpath": "/home/test/File2.zip",
            "MD5": "dbb11b2095c952ff1d4b284523d3085f",
            "name": "File2"
        }
    ]
}

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

代码语言:javascript
复制
{
    "files": [
        {
            "nameandpath": "/home/test/File1.zip",
            "MD5": "e226664e39dc82749d05d07d6c3078b9",
            "name": "File1"
        },
        {
            "nameandpath": "/home/test/File2.zip",
            "MD5": "dbb11b2095c952ff1d4b284523d3085f",
            "name": "File2"
        }
        # block added because the file tested wasn't present in json file
        {
            "nameandpath": "/home/test/File3.zip",
            "MD5": "dbb11b2095c952ff1d4b284523d3085f",
            "name": "File3"
        }
    ]
}

我无法更新现有行,也无法测试添加新行。

你能帮帮我吗?

我怎么能做这样的事情呢?

到目前为止我的代码如下:

代码语言:javascript
复制
# 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
EN

回答 1

Stack Overflow用户

发布于 2017-01-19 19:05:38

我不清楚你到底在纠结什么。下面是我将如何组织代码,也许这会有所帮助:

代码语言:javascript
复制
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,它们类似,但更安全。

票数 0
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/41725242

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档