有人可以通过Open()&#x27给出ELI5的说明。当我腌制时在做吗?

发布于 2025-01-18 15:37:16 字数 401 浏览 2 评论 0原文

我已经多次使用过这种语法来腌制文件,但事实是我不明白实际发生了什么。我只知道这给了我想要的结果。

with open('some_model_name.pickle', 'wb') as to_write:
   pickle.dump(some_model_object, to_write)

但是实际上发生了什么?如果我不指定WB怎么办?什么是作为to_write

当我回到我的模型时,也一样

with open(path+'some_model_name.pickle', 'rb') as to_read:
  some_model_object = pickle.load(to_read)

I've used this syntax many, many times to pickle a file, but the truth is I don't understand what is actually happening. I just know that it gives me the result that I want.

with open('some_model_name.pickle', 'wb') as to_write:
   pickle.dump(some_model_object, to_write)

But what is actually happening? What if I don't specify wb? What is as to_write?

Same with when I read my model back in:

with open(path+'some_model_name.pickle', 'rb') as to_read:
  some_model_object = pickle.load(to_read)

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

⊕婉儿 2025-01-25 15:37:16

“wb”是“以二进制模式写入”的简写。如果您不指定“wb”,您将获得默认模式open,即以文本模式读取。在这种情况下,对 pickle.dump 的调用将会失败,因为文件是以只读模式打开的,并且您尝试写入一些字节。

绑定as to_write 意味着将open 调用的返回值分配给名为to_write 的局部变量。在不使用上下文管理器(“with 语句”)的情况下执行相同操作的类似方法可能如下所示:

try:
    to_write = open('some_model_name.pickle', 'wb')
    pickle.dump(some_model_object, to_write)
finally:
    to_write.close()

这是一个简化版本,本答案末尾的文档链接中给出了更完整的等效版本。

问题中显示的第二个代码块是类似的,除了它以“读取二进制”模式“rb”打开文件“some_model_name.pickle”,这是合适的,因为 pickle.load (读取字节)此处使用而不是 pickle.dump (写入字节)。

我所描述部分的相关文档链接:

The "wb" is shorthand for "write in binary mode". If you don't specify "wb" you will get the default mode of open, which is read in text mode. In that case, the call to pickle.dump would then fail, because the file was opened in read-only mode and you try to write some bytes.

The binding as to_write means to assign the return-value of the open call to a local variable named to_write. A similar way to do the same thing, without using a context manager ("with statement") may look like:

try:
    to_write = open('some_model_name.pickle', 'wb')
    pickle.dump(some_model_object, to_write)
finally:
    to_write.close()

This is a simplified version, a more complete equivalent is given in the docs link at the end of this answer.

The second code-block shown in the question is analogous, except it's opening the file "some_model_name.pickle" in "read binary" mode "rb", which is appropriate because pickle.load (reading bytes) is used here instead of pickle.dump (writing bytes).

Relevant docs links for the parts I've described:

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文