Linux查看本地Python文档

Python3.x下pickle模块的注意点

regding posted @ 2012年1月11日 16:24 in Script with tags python3 pickle , 3328 阅读

公司win xp机器上的Python环境是3.0v的。

学Python的文件操作部分,对于Python对象持久化,

Python自带有一个pickle模块,用于把Python的对象(包括内置类型和自定义类型)

写入到文件中。

 

在learning Python书中的示例是通过

import pickle

D = {1:1, 2:2}
F = open('file.txt', 'w')
pickle.dump(D, F)
F.close()

 

但是在个人的环境中做实验时,出现如下异常

TypeError: can't write bytes to text stream

通过Google查,有人说因为Python3中做了修改,

所以应该使用下列方式打开文件

F = open('file.txt', 'wb')

给出的原因是:“因为存储的是对象,必须使用二进制形式写进文件。”

 

那么也就顺便查了一下文档。

The file argument must have a write() method that accepts a single bytes argument. It can thus be a file object opened for binary writing, a io.BytesIO instance, or any other custom object that meets this interface

 

这也就是说明了,如果想要通过pickle模块去持久化Python的对象,那么需要以二进制的方式写入/读取文档。

 

 

  • 无匹配
Emma 说:
2023年1月21日 01:24

The pickle module under Python 3.x is an incredibly useful tool for writing and reading Python objects to and from a file. Whether you're dealing with built-in or custom types, the pickle real estate property San Francisco module can make file operations simpler and more efficient. For those on Windows XP machines, the Python environment is already set up to 3.0v. Overall, if you're looking to persist data with Python, the pickle module is the way to go.

seo service london 说:
2024年1月16日 03:30

Good post. Thanks for sharing with us. I just loved your way of presentation. I enjoyed reading this .Thanks for sharing and keep writing


登录 *


loading captcha image...
(输入验证码)
or Ctrl+Enter