Python 列表理解删除列表中的字典

Python List Comprehension to Delete Dict in List

{
   "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)

它部分起作用,因为凭证部分中的所有内容看起来都很正常,但它会在末尾附加一个 st运行ge 复制的片段,从而打破 JSON。假设我正在删除 G运行t 并且我 运行 这段代码,我的 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 比较陌生。

您可以关闭文件,然后以只写方式打开文件,这会在写入新内容之前清除原文件的内容。:

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)

写入后需要截断文件:

 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()

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)