我正在嘗試洗掉 json 檔案中串列中的單個索引
檔案
{
"0": [
"0",
"1",
"2",
"3"
]
}
該程式
import json
with open("main.json","r") as jsonfile:
jsonfile = json.load(jsonfile)
key = "0"
index = int(input("which index u want to remove: "))
with open("main.json","r ") as f:
if key in jsonfile:
#jsonfile[key].append(str(index))
del jsonfile[key][index]
json.dump(jsonfile,f,indent=3)
這是程式洗掉索引后的樣子:

請說如何解決這個問題。我正在使用 repl.it
uj5u.com熱心網友回復:
問題在于保存檔案。首先,"w"不要"r "因為你沒有閱讀而使用。其次,要保存它,只需使用:
f.write(json.dumps(jsonfile))
請參閱:洗掉 JSON 物件中的元素
uj5u.com熱心網友回復:
將“r ”更改為“w”以再次寫入整個檔案。
with open("main.json","w") as f:
if key in jsonfile:
#jsonfile[key].append(str(index))
del jsonfile[key][index]
json.dump(jsonfile,f,indent=3)
uj5u.com熱心網友回復:
錯誤在于“r ”應該是“w”:
import json
with open("main.json","r") as jsonfile:
jsonfile = json.load(jsonfile)
key = "0"
index = int(input("which index u want to remove: "))
with open("main.json","w") as f:
if key in jsonfile:
#jsonfile[key].append(str(index))
del jsonfile[key][index]
json.dump(jsonfile,f,indent=3)
在 replit.com 上作業,我知道因為那是我使用的。
轉載請註明出處,本文鏈接:https://www.uj5u.com/qiye/357904.html
上一篇:如何避免鏈接串列中的物件?
