Python列表理解,删除列表中的Dict

2024-07-03 06:35:41 发布

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

{
   "Credentials": [
      {
         "realName": "Jimmy John",
         "toolsOut": null,
         "username": "291R"
      },
      {
         "realName": "Grant Hanson",
         "toolsOut": null,
         "username": "98U9"
      },
      {
         "realName": "Gill French",
         "toolsOut": null,
         "username": "F114"
      }
   ]
}    

我有一个如上格式的json文件,我正试图让一个函数根据用户输入的用户名删除一个条目。我希望文件被覆盖,删除条目

我试过这个:

 def removeUserFunc(SID):
            print(SID.get())
            with open('Credentials.json','r+') as json_file:
                data = json.load(json_file)
                data['Credentials'][:] = [item for item in data['Credentials'] if item['username'] != SID.get()]
                json_file.seek(0)
                json.dump(data,json_file,indent=3,sort_keys=True)

它在一定程度上起作用,因为凭证部分中的所有内容看起来都很正常,但它在末尾附加了一个奇怪的复制片段,破坏了JSON。假设我删除了Grant并运行了此代码,我的JSON如下所示:

{
   "Credentials": [
      {
         "realName": "Marcus Koga",
         "toolsOut": null,
         "username": "291F"
      },
      {
         "realName": "Gill French",
         "toolsOut": null,
         "username": "F114"
      }
   ]
}        "realName": "Gill French",
         "toolsOut": null,
         "username": "F114"
      }
   ]
}

我对Python和编辑JSON也比较陌生


Tags: jsondatausernameitemnullfilecredentialsfrench
3条回答

写入后需要截断文件:

 def removeUserFunc(SID):
            print(SID.get())
            with open('Credentials.json','r+') as json_file:
                data = json.load(json_file)
                data['Credentials'][:] = [item for item in data['Credentials'] if item['username'] != SID.get()]
                json_file.seek(0)
                json.dump(data,json_file,indent=3,sort_keys=True)
                json_file.truncate()

您可以关闭该文件,然后仅打开该文件进行写入,这将在写入新内容之前清除原始文件的内容:

def removeUserFunc(SID):
    # open file for reading
    with open('Credentials.json','r') as json_file:
        # read the data to variable:
        data = json.load(json_file)

    # open file for writing:
    with open('Credentials.json','w') as json_file:
        data['Credentials'][:] = [item for item in data['Credentials'] if item['username'] != SID.get()]
        json.dump(data,json_file,indent=3,sort_keys=True)

file.seek(0)只移动文件指针,但不更改文件的长度。因此,如果不覆盖文件的全部内容,将留下剩余内容。在写入之前,使用file.truncate()将文件长度设置为零

json_file.seek(0)
json_file.truncate()  # set file length to zero
json.dump(data,json_file,indent=3,sort_keys=True)

相关问题 更多 >