python3文件读写模式_python 3.1 兼容问题一则:pickle 操作时文件读写模式

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时)。

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值