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']

未完



發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章