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

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

我试过这个:

 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)

它部分工作,因为 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"
      }
   ]
}

我对 Python 和编辑 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_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)

暂无
暂无

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

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