有没有办法将没有 'write' 属性的 python 对象保存到磁盘

Is there a way to save python objects to disk, that do not have a 'write' attribute

我看到 pickle 是将 python 对象保存到磁盘的标准方法。然而,当我尝试这个

pickle.dump( embeddings , 'embeddings.pickle', pickle.HIGHEST_PROTOCOL)

我明白了

---------------------------------------------------------------------------
TypeError                                 Traceback (most recent call last)
<ipython-input-36-ae20bbf8c8a9> in <module>()
----> 1 pickle.dump( embeddings , 'embeddings.pickle', pickle.HIGHEST_PROTOCOL)

TypeError: file must have a 'write' attribute

没有 'write' 属性的 python 对象有办法吗

pickle.dump() 的第二个参数必须是打开的文件,而不是文件名。

with open('embeddings.pickle', 'wb') as f:
    pickle.dump( embeddings , f, pickle.HIGHEST_PROTOCOL)