我正在制作一個播放串列網站,可以創建顯示和洗掉播放串列和歌曲。我正在使用 JSON 檔案來存盤資料。唯一不起作用的功能是洗掉歌曲功能。
這是我的 JSON 檔案
"Playlists": [
{
"ID": 1,
"Name": "Car Boosted",
"Songs": [
{
"Name": "Dusk Till Dawn",
"Artist": "Sia",
"Link": "https://www.youtube.com/watch?v=6ADdqsvlqtU"
},
{
"Name": "Blinding Lights",
"Artist": "The Weekend",
"Link": "https://www.youtube.com/watch?v=4NRXx6U8ABQ"
}
],
"Date": "16 / 03 / 2022"
},
{
"ID": 2,
"Name": "Workout Playlists",
"Songs": [
{
"Name": "Dusk Till Dawn",
"Artist": "Sia",
"Link": "https://www.youtube.com/watch?v=6ADdqsvlqtU"
},
{
"Name": "Blinding Lights",
"Artist": "The Weekend",
"Link": "https://www.youtube.com/watch?v=4NRXx6U8ABQ"
},
{
"Name": "Till I Collapes",
"Artist": "Eminem",
"Link": "https://www.youtube.com/watch?v=Obim8BYGnOE"
},
{
"Name": "Lose Yourself",
"Artist": "Eminem",
"Link": "https://www.youtube.com/watch?v=_Yhyp-_hX2s"
}
],
"Date": "25 / 04 / 2022"
}
]
我正在使用播放串列的 ID 和歌曲的索引在串列中找到它并使用它來洗掉它。這是我的“洗掉歌曲”功能:
def deleteSongFromJson(songID, pid):
"""deletes Songs Form Playlist
Args:
songID (int): ID Of Song
id (itn): ID Of Playlist
"""
pid = int(pid)
songID = int(songID)
with open('databse.json','r ') as file:
data = json.load(file)
playlists = data['Playlists']
for playlist in playlists:
if playlist['ID'] == id:
songs = playlist["Songs"]
del songs[songID]
file.seek(0)
json.dump(data, file, indent = 4)
當我運行該函式時,它會從正確的播放串列中洗掉歌曲,但會粘貼串列的最后一位并粘貼到 JSON 檔案的底部。
例如
"Name": "Blinding Lights",
"Artist": "The Weekend",
"Link": "https://www.youtube.com/watch?v=4NRXx6U8ABQ"
}
],
"Date": "17 / 05 / 2022"
}
]
"Artist": "The Weekend",
"Link": "https://www.youtube.com/watch?v=4NRXx6U8ABQ"
}
],
"Date": "17 / 05 / 2022"
}
]
uj5u.com熱心網友回復:
我認為您的問題是嘗試一次性讀取和寫入檔案,這可能會導致奇怪的游標問題。
嘗試重構您的代碼以具有兩個單獨open的陳述句,如下所示(未經測驗):
def deleteSongFromJson(songID, pid):
"""deletes Songs from Playlist
Args:
songID (int): ID Of Song
id (itn): ID Of Playlist
"""
pid = int(pid)
songID = int(songID)
with open('databse.json','r') as file:
data = json.load(file)
for playlist in data['Playlists']:
if playlist['ID'] == id:
del playlist["Songs"][songID]
with open('databse.json','w') as file:
json.dump(data, file, indent=4)
轉載請註明出處,本文鏈接:https://www.uj5u.com/qukuanlian/479615.html
