Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Programming Python for absolute beginners: Chapter 7 Storing Complex Data

Tags:

python-3.x

I'm learning from "Python programming for the absolute beginner" and have been having fun. The book is written for Python 2.7 (i think), but I've been using Python 3 and translating the code, which is been a fun challenge.

I recently ran into a problem I'm not sure how to fix. On the section labeled: "Pickling Data and Writing It to a File" There's an example where you run the following code:

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()

I translated it to this (for 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()

BUT, i get this error/output from 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

Any ideas?

like image 647
AlphaTested Avatar asked Feb 12 '11 20:02

AlphaTested


1 Answers

You are trying to write bytes, ie binary data, to a text file, which will only accept str. Change the file opening flags, it should be:

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

With the b flagging it as a binary file, which then will accept bytes.

This is in fact a bug in the book. The binary flag should really be there in the Python 2 code as well.

like image 179
Lennart Regebro Avatar answered Nov 04 '22 01:11

Lennart Regebro