第七色在线视频,2021少妇久久久久久久久久,亚洲欧洲精品成人久久av18,亚洲国产精品特色大片观看完整版,孙宇晨将参加特朗普的晚宴

為了賬號安全,請及時(shí)綁定郵箱和手機(jī)立即綁定
已解決430363個(gè)問題,去搜搜看,總會(huì)有你想問的

如何允許用戶通過 Python 使用 Json 從 .txt 文件中刪除對象

如何允許用戶通過 Python 使用 Json 從 .txt 文件中刪除對象

動(dòng)漫人物 2022-06-22 17:57:14
問題總結(jié)我制作了這個(gè)地址簿,將用戶輸入轉(zhuǎn)儲(chǔ)到 .txt 文件中,我希望能夠讓用戶刪除保存在地址簿(.txt 文件)中的人,如果他們愿意的話。我該怎么辦?基本上我只是希望將其從 .txt 文件中擦除,而無需自己手動(dòng)執(zhí)行,也無需刪除其他名稱和信息我試過的這是我在程序中輸入的一些代碼,試圖讓用戶執(zhí)行刪除某人的任務(wù),但它會(huì)運(yùn)行順利,但是當(dāng)我去檢查 .txt 文件時(shí),這個(gè)人和他們的信息仍然存在。if input("would you like to remove someone from the registry?('Yes' or 'No')") ==  "Yes":    who_delete = input("Who would you like to remove?")del who_delete(我在 book = {} 行下面列出的代碼上輸入了上面的代碼。)#current codeimport jsonbook = {}Name = input("Enter a name")book[Name] = {"Address": input("Enter an adress"),"Phone": input("Enter a phone number"),}s=json.dumps(book, indent=2)with open("C://Users//user//OneDrive//Desktop//Library//Coding and Programming Projects//Self Projects//Address Book//addressbook.txt", "a") as f:    f.write(s)預(yù)期結(jié)果:在運(yùn)行程序時(shí)通過 shell 從 .txt 文件中刪除一個(gè)對象,而無需在 .txt 文件上手動(dòng)執(zhí)行此操作實(shí)際結(jié)果:對象未從 .txt 文件中刪除
查看完整描述

2 回答

?
慕婉清6462132

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)


查看完整回答
反對 回復(fù) 2022-06-22
?
米琪卡哇伊

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


查看完整回答
反對 回復(fù) 2022-06-22
  • 2 回答
  • 0 關(guān)注
  • 127 瀏覽
慕課專欄
更多

添加回答

舉報(bào)

0/150
提交
取消
微信客服

購課補(bǔ)貼
聯(lián)系客服咨詢優(yōu)惠詳情

幫助反饋 APP下載

慕課網(wǎng)APP
您的移動(dòng)學(xué)習(xí)伙伴

公眾號

掃描二維碼
關(guān)注慕課網(wǎng)微信公眾號