TypeError:使用pickle需要一个整数(获取类型_io.BufferedWriter)

10 python serialization file pickle

代码:

import pickle
test = 3

>>> with open('test', 'wb') as file:
...     pickle.dumps(test, file)
Run Code Online (Sandbox Code Playgroud)

和错误报告意外.

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

这里发生了什么?

cs9*_*s95 14

你使用的是错误的功能.这是文档:

dumps(obj, protocol=None, *, fix_imports=True)
Run Code Online (Sandbox Code Playgroud)

返回该对象的腌渍表示作为bytes对象.

dumps将传递的对象转换为bytes并返回它.您得到的错误是将文件参数传递给.dump期望为酸洗协议的文件,该文件应该是一个整数.

您将要使用pickle.dump,实际转储到文件:

dump(obj, file, protocol=None, *, fix_imports=True)
Run Code Online (Sandbox Code Playgroud)

obj将打开的表示写入打开的文件对象file.

with open('test', 'wb') as file:
    pickle.dump(test, file)
Run Code Online (Sandbox Code Playgroud)