为绝对初学者编程Python:第7章存储复杂数据

时间:2011-02-12 20:01:24

标签: python-3.x

我正在学习“绝对初学者的Python编程”并且一直很开心。这本书是为Python 2.7编写的(我认为),但我一直在使用Python 3并翻译代码,这是一个有趣的挑战。

我最近遇到了一个问题,我不确定如何修复。在标记为“Pickling Data并将其写入文件”的部分中,您可以运行以下代码:

import cPickle, shelve
print "Pickling lists." variety = ["sweet", "hot", "dill"]
shape = ["whole", "spear", "chip"]
brand = ["Claussen", "Heinz", "Vlassic"]
pickle_file = open("pickles1.dat", "w")
cPickle.dump(variety, pickle_file)
cPickle.dump(shape, pickle_file)
cPickle.dump(brand, pickle_file)
pickle_file.close()

我把它翻译成了这个(对于python 3)

import pickle, shelve
print ("Pickling lists.")
variety = ["sweet", "hot", "dill"]
shape = ["whole", "spear", "chip"]
brand = ["Classen", "Heinz", "Vlassic"]
pickle_file = open("pickles1.dat", "w")
pickle.dump(variety, pickle_file)
pickle.dump(shape, pickle_file)
pickle.dump(brand, pickle_file)
pickle_file.close()

但是,我从IDLE获得此错误/输出:

Pickling lists.
Traceback (most recent call last):
File "/Users/hypernerdcc/Documents/pickles.py", line 11, in <module>
pickle.dump(variety, pickle_file)
File
"/Library/Frameworks/Python.framework/Versions/3.1/lib/python3.1/pickle.py",
line 1345, in dump
Pickler(file, protocol, fix_imports=fix_imports).dump(obj)
TypeError: must be str, not bytes

有什么想法吗?

1 个答案:

答案 0 :(得分:8)

您正在尝试将字节(即二进制数据)写入文本文件,该文件只接受str。更改文件打开标志,应该是:

pickle_file = open("pickles1.dat", "wb")

b将其标记为二进制文件,然后接受字节。

这实际上是本书中的一个错误。二进制标志也应该存在于Python 2代码中。