我正在嘗試製作一個程序,收集大量有關當某個樂隊的某些玩家在聖誕節時可用於街拍的數據,而且我正在掙扎讓泡菜功能做我想做...的數據存儲在下面的類的類的實例,Player
:Python 3:醃製和UnPickling類實例返回「沒有持久負載」錯誤
import pickle
class Player():
def __init__(self, name, instrument, availability):
self.Name=name
self.Instrument=instrument
self.Availability=availability
的球員名單,PlayerList
起初被定義爲一個空列表,我已經定義了一個函數,AddPlayer
將初始化一個類實例,並將玩家的詳細信息存儲爲屬性...
PlayerList=[]
def AddPlayer(PlayerList, name, instrument, availability):
NewPlayer = Player(name, instrument, availability)
PlayerList.append(NewPlayer)
print("Player "+name+" has been added.\n\n")
我再有,當用戶退出程序存儲的球員名單功能...
def StartProgram(PlayerList):
while True:
choice=input("Would you like to:\n1 Add a Player?\n2 Quit?\n")
if choice=="1":
## Adds the details of the Player using the above function
AddPlayer(PlayerList, "Test Player", "Instrument", ["1st Dec AM"])
StartProgram(PlayerList)
elif choice=="2":
file=open("BuskingList.txt", "wb")
file=open("BuskingList.txt", "ab")
def AddToList(PlayerList):
print("PlayerList: "+str(PlayerList))
HalfPlayerList=PlayerList[:5]
## For some reason, pickle doesn't like me trying to dump a list with more than
## 5 values in it, any reason for that?
for Player in HalfPlayerList:
print("Player: "+str(Player))
PlayerList.remove(Player)
## Each player removed from original list so it's only added once.
print("HalfPlayerList: "+str(HalfPlayerList))
pickle.dump(HalfPlayerList, file)
if len(PlayerList) !=0:
AddToList(PlayerList)
## Recursive function call while there are still players not dumped
AddToList(PlayerList)
file.close()
quit()
else:
print("Enter the number 1, 2, or 3.\n")
StartProgram(PlayerList)
和最後在節目開始時的功能運行加載所有玩家的信息。 ..
def Start():
file=open("BuskingList.txt", "rb")
print("File contains: "+str(file.readlines()))
PlayerList=[]
CheckForPlayers=file.read()
if CheckForPlayers!="":
file=open("BuskingList.txt", "rb")
ListOfLists=[]
for line in file:
ToAppend=pickle.load(file)
ListOfLists.append(ToAppend)
for ListOfPlayers in ListOfLists:
for Player in ListOfPlayers:
PlayerList.append(Player)
StartProgram(PlayerList)
print("When entering dates, enter in the form 'XXth Month AM/PM'\n")
Start()
當程序第一次運行(提供BuskingList.txt
存在),該程序運行正常,添加一個名字的作品和酸洗和退出顯然作品爲之傾倒。然而,在重新啓動程序時,它失敗與下面的錯誤讀取存儲的數據...
File contains: [b'\x80\x03]q\x00c__main__\n', b'Player\n', b'q\x01)\x81q\x02}q\x03(X\x04\x00\x00\x00Nameq\x04X\x0b\x00\x00\x00Test Playerq\x05X\n', b'\x00\x00\x00Instrumentq\x06h\x06X\x0c\x00\x00\x00Availabilityq\x07]q\x08X\n', b'\x00\x00\x001st Dec AMq\tauba.']
Traceback (most recent call last):
File "I:/Busking/Problem.py", line 63, in <module>
Start()
File "I:/Busking/Problem.py", line 54, in Start
ToAppend=pickle.load(file)
_pickle.UnpicklingError: A load persistent id instruction was encountered,
but no persistent_load function was specified.
我已經做了一些研究,發現這個永久ID說大話不應該是一個問題,爲什麼它出現在這裏?另外,爲什麼酸洗時列表上的五個值會受到限制?任何幫助,將不勝感激。
只是試圖實現你的建議......同時,我問了關於列表大小的問題,作爲事後的想法......做另一個項目時,取消超過5個值的列表,我一直得到EOFerrors ... – rjmcf
這就是太棒了,這是工作!非常感謝你。 :) – rjmcf