如何在python中取消文件?

时间:2013-05-10 18:30:24

标签: python pickle

例如我有两个词典
这就是我的尝试:

def unpickle(filename):
    open = open(filename, "rb")
    Dic1 = cPickle.load(open)
    Dic2 = cPickle.load(open)
    open.close()
    return Dic1,Dict2

但是当我想在另一个函数中进行unpickle时它会出错。 它表示无效的加载密钥,'m'

1 个答案:

答案 0 :(得分:2)

啊,所以发生的事情是你打开文件一次并关闭它一次,但是使用它两次。我采用了自己的unpickle函数并尝试创建两个东西,它给了我一个错误。

这是我在使用您之前的功能时遇到的错误:

Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
  File "<stdin>", line 4, in pickleLoad
  File "/opt/local/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/pickle.py", line 1378, in load
    return Unpickler(file).load()
  File "/opt/local/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/pickle.py", line 858, in load
    dispatch[key](self)
  File "/opt/local/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/pickle.py", line 880, in load_eof
    raise EOFError
EOFError

但是当我这样编辑它时,它运行良好:

import cPickle
def unpickle(filename):
    open_first = open(filename, "rb")
    Dic1 = cPickle.load(open_first)
    open_again = open(filename, "rb")
    Dic2 = cPickle.load(open_again)
    open_first.close()
    open_again.close()
    return Dic1,Dic2

但是你的函数在两个变量中返回相同的内容,因为我们只有一个参数,即filename ..来解开文件:

def unpickle(filename):
    f = open(filename, "rb")
    d = cPickle.load(f)
    f.close()
    return d