首页 > 解决方案 > TypeError:文件必须具有在 Python3 中运行的 'read' 和 'readline' 属性

问题描述

我已经搜索过这种类型的错误,尝试尽可能多地修复,但是这个错误并没有消失

Traceback (most recent call last):
  File "rbm.py", line 419, in <module>
    learn_letters()
  File "rbm.py", line 350, in learn_letters
    import rbm
  File "/Users/thienhua/Desktop/usingnow/coding/sachml/Ch17/rbm.py", line 423, in <module>
    test_rbm()
  File "/Users/thienhua/Desktop/usingnow/coding/sachml/Ch17/rbm.py", line 259, in test_rbm
    train_set = pickle.load(file)
TypeError: file must have 'read' and 'readline' attributes

这是我卡住的行代码:

def test_rbm():
   import rbm
   import pickle

   # Load the dataset
   with open('mnist.pkl', 'rb') as f:
      file = pickle._Unpickler(f)
      file.encoding = 'latin1'
      train_set = pickle.load(file)
      valid_set = pickle.load(file)
      test_set = pickle.load(file)
      #train_set, valid_set, test_set = pickle.load(file)
      file.close()

   r = rbm.rbm(28*28,100,inputs = train_set[0][:100,:],momentum=0.4,nCDsteps=3,nepochs=5000)
   r.contrastive_divergence(train_set[0][:100,:])

我目前使用 python 3.8。非常感谢你的帮助。

标签: pythonpickle

解决方案


问题是它pickle.load接受类似文件的对象,但pickle._Unpickler()不返回那种对象(它返回的实例class _Unpickler,它没有'read'和'readline'属性)。如果您将 python 对象腌制到某个文件中,则必须通过pickle.load('/path/to/pickle_file'). 有关https://docs.python.org/3/library/pickle.html的更多信息


推荐阅读