2

非常新手程序员,对不起,如果这是愚蠢的或者我的英语是错误的。所以,我有我正在写的这个命令行通讯录。它由一个字典组成,该字典包含一个以键作为名称变量的对象,并且每个对象都有与之关联的变量,例如人名,电子邮件等......它可以工作,但现在我正在尝试制作它使用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

我不明白这一点。我实际上已经写了这个程序,它正在使用内存节省,但我不小心删除了它。怎么了?

4

2 回答 2

4

pickle点击EOF肯定会告诉文件已损坏(可能被截断,可能写入操作失败)。

如果您将其上传到某个地方,我们也许可以推断出它到底有什么问题。在最坏的情况下,您将不得不窥视内部并推断那里的数据以手动重新输入。

这是使用不可读格式而不注意其完整性的代价(例如,写入另一个文件并仅在保存成功后将其移动到原始文件上)。

更新:

如果您想从一个新的“空”文件开始,则处理文件丢失的情况并生成一个空的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
于 2015-07-15T19:21:54.233 回答
2

我看不出您的代码有任何明显错误,但如果您只想存储这样的键/值对,您可能应该使用搁置模块而不是自制解决方案。

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()    
于 2015-07-15T19:10:49.760 回答