[英]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.