- html - 出于某种原因,IE8 对我的 Sass 文件中继承的 html5 CSS 不友好?
- JMeter 在响应断言中使用 span 标签的问题
- html - 在 :hover and :active? 上具有不同效果的 CSS 动画
- html - 相对于居中的 html 内容固定的 CSS 重复背景?
我正在尝试制作一个程序,收集有关乐队中的某些玩家何时可以在今年圣诞节进行街头表演的大量数据,并且我正在努力让 pickle 函数执行我想要的操作...数据存储在以下类的类实例中,Player
:
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 存在),程序运行良好,添加名称有效,对其进行 pickle 并在退出时转储它显然有效。但是,当程序重新启动时,它无法读取存储的数据,并出现以下错误...
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 malarkey 不应该成为问题,那么为什么它会出现在这里呢?另外,为什么 pickle 时列表上有五个值限制?任何帮助将不胜感激。
最佳答案
您首先使用.readlines()
读取列表:
print("File contains: "+str(file.readlines()))
然后尝试再次阅读:
CheckForPlayers=file.read()
这行不通;文件指针现在位于文件末尾。快退或重新打开文件:
file.seek(0) # rewind to start
并不是说您需要在此处检查文件内容;让 pickle
为您做这件事。
接下来逐行读取文件:
for line in file:
ToAppend=pickle.load(file)
这不起作用; pickle 格式是二进制,不是面向行的,并且您通过使用迭代来读取,然后通过传入文件对象再次读取。
将文件的读取完全交给 pickle
模块:
with open("BuskingList.txt", "rb") as infile:
ToAppend=pickle.load(file)
您还在代码中提到:
## For some reason, pickle doesn't like me trying to dump a list with more than
## 5 values in it, any reason for that?
Pickle 对于任何列表大小都没有问题,没有理由将您的玩家列表分成五个部分。您没有说明遇到了什么问题,但列表中的项目数不可能是原因:
>>> import pickle
>>> with open('/tmp/test.pickle', 'wb') as testfile:
... pickle.dump(range(1000), testfile)
...
>>> with open('/tmp/test.pickle', 'rb') as testfile:
... print len(pickle.load(testfile))
...
1000
这存储并重新加载了 1000 个整数的列表。
关于Python 3 : Pickling and UnPickling class instances returning "no persistent load" error,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/19985818/
询问 unrelated question我有这样的代码: public boolean equals(Object obj) { if (this == obj) retur
在我之前的一个问题中 js: Multiple return in Ternary Operator我询问了有关使用三元运算符返回多个参数的问题。但是现在参数IsActveUser boolean(t
假设我有一个带有 return 的 if 语句。从效率的角度来看,我应该使用 if(A > B): return A+1 return A-1 或 if(A > B): return
例如考虑以下代码: int main(int argc,char *argv[]) { int *p,*q; p = (int *)malloc(sizeof(int)*10); q
PyCharm 对这段代码发出警告,说最后一个返回是不可访问的: def foo(): with open(...): return 1 return 0 如果 ope
我想实现这样的目标: 如果在返回 Json 的方法中抛出异常,则返回 new Json(new { success = false, error = "unknown"}); 但如果方法返回 View
它是多余的,但我正在学习 JS,我想知道它是如何工作的。 直接从模块返回函数 let func1 = function () { let test = function () {
我不明白我应该使用什么。我有两页 - intro.jsp(1) 和 booksList.jsp(2)。我为每一页创建了一个 Controller 类。第一页有打开第二页的按钮:
我最近在 Joomla 组件(Kunena,更准确地说是 Kunena)中看到这段代码,那么使用 $this->return VS 简单的 return 语句有什么区别. 我已经用谷歌搜索了代码,但没
我的类实现了 IEnumerable。并且可以编译这两种方式来编写 GetEnumerator 方法: public IEnumerator GetEnumerator() { yield r
我只是在编码,我想到了一个简单的想法(显然是问题),如果我有一个像这样的函数: int fun1(int p){ return(p); } 我有一个这样的函数: int fun1(int p){
这个问题在这里已经有了答案: What does the comma operator do in JavaScript? (5 个答案) 关闭 9 年前。 function makeArray
假设我写了一个 for 循环,它将输出所有数字 1 到 x: x=4 for number in xrange(1,x+1): print number, #Output: 1 2 3 4 现
我最近在这个 Apache Axis tutorial example. 中看到了下面的一段代码 int main() { int status = AXIS2_SUCCESS; ax
function a(){ return{ bb:"a" } } and function a(){ return { bb:"a" } } 这两个代码有什么区别吗,如果有请
function a() { return 1; } function b() { return(1); } 我在 Chrome 的控制台中测试了上面的代码,都返回了 1。 function c()
考虑这三个函数: def my_func1(): print "Hello World" return None def my_func2(): print "Hello World"
这可能是一个愚蠢的问题,但我正在努力,如果有一种简明的方法来测试函数的返回结果,如果它不满足条件,则返回该值(即,传递它)。。现在来回答一个可能的问题,是的,我正在寻找的类似于例外提供的东西。然而,作
我正在测试一个函数,并尝试使用 return 来做什么,并在 PowerShell 5.1 和 PwSh 7.1 中偶然发现了一个奇怪的问题,即 return cmdlet似乎不适合在团体中工作: P
这个问题已经有答案了: Return in generator together with yield (2 个回答) Why can't I use yield with return? (5 个回
我是一名优秀的程序员,十分优秀!