非常新手程序员,对不起,如果这是愚蠢的,或者我的英语错了。所以,我正在编写这个命令行地址簿。它由一个字典组成,该字典包含一个以键为名称变量的对象,每个对象都有与之关联的变量,如人名,电子邮件等......它有效,但现在我正在尝试使用pickle使其在内存中持久存储字典。
def create_person():
"""Adds an instance object of the Person class to the dictionary persons. persons is a global variable, that has been created previously. DATA is a variable that points to a file named test.data that exists in the same directory as the script."""
name = raw_input("Enter the person's name here: ")
email = raw_input("Enter the person's email here: ")
phone = raw_input("Enter the person's phone here: ")
address = raw_input("Enter the person's address here: ")
f = open(DATA, "rb")
persons = pickle.load(f) #assign whatever is saved in the dictionary in persistent memory to global variable persons, which is empty at this point in the beginning
f.close()
persons[name] = Person(name, email, phone, address)
f = open(DATA, "wb")
pickle.dump(persons, f)
f.close()
但是,我收到此错误:
Traceback (most recent call last):
File "testpickle.py", line 85, in <module>
main()
File "testpickle.py", line 40, in main
create_person()
File "testpickle.py", line 20, in create_person
persons = pickle.load(f)
File "/home/pedro/anaconda/lib/python2.7/pickle.py", line 1378, in load
return Unpickler(file).load()
File "/home/pedro/anaconda/lib/python2.7/pickle.py", line 858, in load
dispatch[key](self)
File "/home/pedro/anaconda/lib/python2.7/pickle.py", line 880, in load_eof
raise EOFError
EOFError
我不明白这一点。我实际上已经编写了这个程序,它正在节省内存,但我意外地删除了它。发生了什么事?
答案 0 :(得分:4)
pickle
点击EOF
肯定告诉文件已损坏(可能是截断的,可能是写操作失败了)。
如果你把它上传到某个地方,我们或许可以推断它到底出了什么问题。在最糟糕的情况下,你必须在里面偷看并推断出那些手动重新输入的数据。
这是您使用不可读格式而不关注其完整性的代价(例如writing to another file and only moving it over the original one after saving succeeded)。
更新:
如果您想从 new,“empty”文件开始,请在文件丢失时处理该情况并生成空dict
。毕竟,文件 最初应该丢失,不是吗?
空文件无效pickle
数据(它必须至少包含有关对象类型的信息)。
这是处理丢失文件的“一种显而易见的方式”((c)Python Zen):
import errno
try: f = open(DATA, "rb")
except IOError,e:
if e[0]==errno.ENOENT: persons={}
else: raise
else:
persons = pickle.load(f)
f.close()
del f
答案 1 :(得分:2)
我没有看到您的代码明显错误,但如果您只想存储这样的键/值对,您可能应该使用shelve模块而不是自制的解决方案
import shelve
persons = shelve.open(DATA)
def create_person():
"""Adds an instance object of the Person class to the dictionary persons. persons is a global variable, that has been created previously. DATA is a variable that points to a file named test.data that exists in the same directory as the script."""
name = raw_input("Enter the person's name here: ")
email = raw_input("Enter the person's email here: ")
phone = raw_input("Enter the person's phone here: ")
address = raw_input("Enter the person's address here: ")
persons[name] = Person(name, email, phone, address)
while more_people:
create_person()
persons.close()