【发布时间】:2015-03-14 19:20:45
【问题描述】:
我正在创建一个程序,将玩家的高分存储在街机中。 我为此使用的列表称为 PlayerID,因为它包含唯一 ID 和其他信息,例如他们在每场比赛中的高分。每当我尝试从玩家列表中成功删除字典时,它都无法正常工作,会删除多个配置文件。
这是我目前使用的代码。 Pickle 被用于数据存储。
with open("playerdata.dat",'rb') as f:
PlayerID = pickle.load(f)
while True:
try:
SearchID= int(input("Enter the ID of the profile you are removing")) # used to check if a wanted user actually exists in the program
except ValueError:
print("You have not provided an integer input, please try again.") #performs type check to ensure a valid input is provided
continue
else:
break
index= 0
position = -1
for Player in PlayerID:
if Player['ID'] == SearchID:
position = index
else:
index = index + 1
try:
PlayerID.pop(position)
except IndexError:
print("The ID provided does not exist.")
print("The user with ID", searchID,", has been deleted")
with open('playerdata.dat','wb') as f:
pickle.dump(playerID,f,pickle.HIGHEST_PROTOCOL)
此外,即使输入的整数 ID 实际上并不存在于 PlayerID 列表中,即使我有 IndexError 代码,它仍会删除多个配置文件。
【问题讨论】:
标签: python list dictionary pickle