类型错误:需要一个整数(得到类型_io.BufferedWriter),使用pickle。

15

代码:

import pickle
test = 3

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

并且意外报告了错误。

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

这里发生了什么事情?

1个回答

27

您正在使用错误的函数。以下是文档:

dumps(obj, protocol=None, *, fix_imports=True)
返回对象的序列化表示为一个bytes对象。

dumps将传递的对象转换为bytes并返回。如果你把文件作为参数传递给.dump,就会出现错误,因为该方法期望的是一个整数类型的pickle协议。

你需要使用pickle.dump,它会将对象实际持久化到文件中:

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

obj的腌制表示写入到打开的文件对象file中。

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

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接