#!/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']

未完



Logo

CSDN联合极客时间,共同打造面向开发者的精品内容学习社区,助力成长!

更多推荐