Chinaunix首页 | 论坛 | 博客
  • 博客访问: 16176
  • 博文数量: 4
  • 博客积分: 1415
  • 博客等级: 上尉
  • 技术积分: 40
  • 用 户 组: 普通用户
  • 注册时间: 2010-05-17 18:30
文章分类

全部博文(4)

文章存档

2010年(4)

我的朋友
最近访客

分类: Python/Ruby

2010-06-27 13:04:59

python 3升级变化颇多,这些天遇到不少,比如 pickle:

import pickle

shoplist = ['apple','food','noodle']

f = open('temp1.txt','wb')
pickle.dump(shoplist,f)
f.close()

f = open('temp1.txt','rb')
print(pickle.load(f))
f.close()

初始调试的时候,按照习惯设置打开模式为‘w’或者‘r’,报错:
Pickler(file, protocol, fix_imports=fix_imports).dump(obj)
TypeError: must be str, not bytes

搜索老外论坛得到原因:
For one thing, don't name your list "list", as that's a reserved word in Python (try list('12345') ), same thing with file... But that modification won't help you.

I'm assuming you've got a new version of Python installed, as the method you're using will only work in earlier versions of python.





pickle.dump(obj, file[, protocol, *, fix_imports=True])¶

Write a pickled representation of obj to the open file object file. This is equivalent to Pickler(file, protocol).dump(obj).

The optional protocol argument tells the pickler to use the given protocol; supported protocols are 0, 1, 2, 3. The default protocol is 3; a backward-incompatible protocol designed for Python 3.0.

Specifying a negative protocol version selects the highest protocol version supported. The higher the protocol used, the more recent the version of Python needed to read the pickle produced.

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.

If fix_imports is True and protocol is less than 3, pickle will try to map the new Python 3.x names to the old module names used in Python 2.x, so that the pickle data stream is readable with Python 2.x.
That's from the 3.1 docs; note that you must open your files in binary mode now. So for dumping use 'wb', and loading use 'rb'.

原来python 3以后必须使用模式‘wb’和‘rb’(load时)。

阅读(962) | 评论(0) | 转发(0) |
0

上一篇:python 3.0.1中的文件及储存器

下一篇:没有了

给主人留下些什么吧!~~