简体   繁体   中英

TypeError: an integer is required (got type _io.BufferedWriter) using pickle

the code:

import pickle
test = 3

>>> with open('test', 'wb') as file:
...     pickle.dumps(test, file)

and error reported unexpectedly.

Traceback (most recent call last):
  File "<stdin>", line 2, in <module>
TypeError: an integer is required (got type _io.BufferedWriter)

What's going on here?

You're using the wrong function. Here's the docs:

 dumps(obj, protocol=None, *, fix_imports=True)

Return the pickled representation of the object as a bytes object.

dumps converts the passed object to bytes and returns it. The error you get is when you pass a file argument to what .dump expects to be the pickling protocol, which is supposed to be an integer.

You'll want to use pickle.dump , which actually dumps to a file:

 dump(obj, file, protocol=None, *, fix_imports=True)

Write a pickled representation of obj to the open file object file .

with open('test', 'wb') as file:
    pickle.dump(test, file)

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