简体   繁体   中英

TypeError: file must have 'read' and 'readline' attributes run in Python3

I have searched about this type of errors, tried to fix as much as I can but still, this error hasn't gone away

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

this is the line code where I got stuck:

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,:])

Im using python 3.8 at the moment. Thank you so much for your help.

The issue is that pickle.load accepts file-like objects, but pickle._Unpickler() doesn't return that kind of object (it returns instance of class _Unpickler , which doesn't have 'read' and 'readline' attrs). If you have pickled python object into some file, you have to load it back through pickle.load('/path/to/pickle_file') . More info on https://docs.python.org/3/library/pickle.html

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM