2 回答

TA貢獻(xiàn)1804條經(jīng)驗(yàn) 獲得超2個(gè)贊
open(path, "a")
將追加(添加)到文件中。假設(shè)您的文件是 json,您需要先讀取內(nèi)容,例如:
with open(path, "r") as f: content = json.load(f)
然后改變內(nèi)容,刪除你不想要的東西,最后寫回文件:
with open(path, "w") as f: json.dump(content, f)

TA貢獻(xiàn)1998條經(jīng)驗(yàn) 獲得超6個(gè)贊
您可以使用pop從字典中刪除鍵及其值。在這種情況下book.pop(Name),應(yīng)刪除名稱及其詳細(xì)信息。
檢查用戶輸入的名稱是否在字典中(并且拼寫正確)可能也是明智之舉,否則在嘗試彈出不存在的鍵時(shí)會(huì)出錯(cuò)。你可以這樣做
input_response = input("would you like to remove someone from the registry?('Yes' or 'No')")
if input_response == "Yes":
who_delete = input("Who would you like to remove?")
if who_delete in books:
books.pop(who_delete)
else:
print(f'Name {who_delete} not in books, please choose a valid key from {list(books.keys())}')
添加回答
舉報(bào)