pickle

#!/usr/bin/env python
# Filename: pickling.py
import os
os.system("cd 'E:\myd\work\Python'")
# import pickle as p
import pickle as p
lang = ['C', 'C++', 'Python']
# the name of the file where we will store the object
langfile = 'lang.dat'
# write to the file
f = open(langfile, 'w')
p.dump(lang, f) # dump the object to a file
f.close()
del(lang) # remove the language list
# read back from the storage
f = open(langfile)
storedlang = p.load(f)
print(storedlang)
在Python3.2中运行有误:“TypeError: must be str, not bytes”

http://stackoverflow.com/questions/5512811/builtins-typeerror-must-be-str-not-bytes

上边提到:

The outfile should be in binary mode.

outFile = open('output.xml', 'wb')

改过这个错误后, 又出现一个错误:“UnicodeDecodeError: 'gbk' codec can't decode bytes in position 0-1: illegal multibyte sequence”

原来第二次读文件的时候没有指定打开方式, 这样就默认以‘r’方式打开了, 实际上应该指定为:‘rb’。

#!/usr/bin/env python
# Filename: pickling.py
import os
os.system("cd 'E:\myd\work\Python'")
# import pickle as p
import pickle as p
lang = ['C', 'C++', 'Python']
# the name of the file where we will store the object
langfile = 'lang.dat'
# write to the file
f = open(langfile, 'wb')
p.dump(lang, f) # dump the object to a file
f.close()
del(lang) # remove the language list
# read back from the storage
f = open(langfile, 'rb')
storedlang = p.load(f)
print(storedlang)
运行结果:

>>> ================================ RESTART ================================
>>> 
['C', 'C++', 'Python']

未完



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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值