简体   繁体   English

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"
      }
   ]
}    

I have a json file formatted as above and I am trying to have a function delete an entry based on the username input from a user.我有一个格式如上的 json 文件,我试图让 function 根据用户输入的用户名删除一个条目。 I want the file to then be overwritten with the entry removed.我希望文件被删除的条目覆盖。

I have tried this:我试过这个:

 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)

It partially works as everything in the Credentials section looks normal, but it appends a strange copied piece to the end that breaks the JSON. Say I was removing Grant and I ran this code, my JSON looks like below:它部分工作,因为 Credentials 部分中的所有内容看起来都很正常,但它在末尾附加了一个奇怪的复制片段,打破了 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"
      }
   ]
}

I am relatively new to Python and editing JSONs as well.我对 Python 和编辑 JSON 比较陌生。

You need to truncate the file after writing:您需要在写入后截断文件:

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

You can close the file and then open the file for writing-only, which will clear the the contents of the original file before writing the new contents.:您可以关闭文件,然后以只写方式打开文件,这将在写入新内容之前清除原始文件的内容。例如:

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) just moves the file pointer but does not change the length of the file. file.seek(0)只是移动文件指针但不改变文件的长度。 So if you do not overwrite the entire contents of the file you will leave residual content.因此,如果您不覆盖文件的全部内容,您将留下残留内容。 Use file.truncate() to set the file length to zero before writing.在写入之前使用file.truncate()将文件长度设置为零。

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM