有人可以通过Open()&#x27给出ELI5的说明。当我腌制时在做吗?
我已经多次使用过这种语法来腌制文件,但事实是我不明白实际发生了什么。我只知道这给了我想要的结果。
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 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
“wb”是“以二进制模式写入”的简写。如果您不指定“wb”,您将获得默认模式
open
,即以文本模式读取。在这种情况下,对 pickle.dump 的调用将会失败,因为文件是以只读模式打开的,并且您尝试写入一些字节。绑定
as to_write
意味着将open
调用的返回值分配给名为to_write
的局部变量。在不使用上下文管理器(“with 语句”)的情况下执行相同操作的类似方法可能如下所示:这是一个简化版本,本答案末尾的文档链接中给出了更完整的等效版本。
问题中显示的第二个代码块是类似的,除了它以“读取二进制”模式“rb”打开文件“some_model_name.pickle”,这是合适的,因为
pickle.load
(读取字节)此处使用而不是pickle.dump
(写入字节)。我所描述部分的相关文档链接:
打开
with
语句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 topickle.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 theopen
call to a local variable namedto_write
. A similar way to do the same thing, without using a context manager ("with statement") may look like: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 ofpickle.dump
(writing bytes).Relevant docs links for the parts I've described:
open
with
statement