[Tutor] TypeError: Need Help
Dave Angel
davea at ieee.org
Thu Nov 19 17:53:49 CET 2009
Ali Sina wrote:
>>> I have Python 3.0 and I'm trying to learn from a pdf document. I followed its instructions >>but I've encountered a problem in its Pickling chapter. This is the code I've written:
>>>
>
> import pickle, shelve
>
> print('Pickling list.')
> variety=['sweet','hot','dill']
> shape=['whole','spear','chip']
> brand=['Claussen','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()
>
> print('\nUnpickling list.')
> pickle_file=open('pickles1.dat','r')
> variety=pickle.load(pickle_file)
> shape=pickle.load(pickle_file)
> brand=pickle.load(pickle_file)
> print(variety,'\n',shape,'\n',brand)
> pickle_file.close()
>
>
>>> But it gives this error:
>>>
>
> Traceback (most recent call last):
> File "E:/Python/pickle it.py", line 11, in <module>
> pickle.dump(variety, pickle_file)
> File "C:\Python31\lib\pickle.py", line 1354, in dump
> Pickler(file, protocol, fix_imports=fix_imports).dump(obj)
> TypeError: write() argument 1 must be str, not bytes
>
>
>>> I read Python Docs but it didn't help me either. I hoping anyone of you could guide me or >>send the revised code itself. Thank you.
>>>
>
>
>>> Regards
>>>
>
>
Three guesses, then a suggestion:
I'd guess that the pdf document you're learning from is aimed at Python
2.x, not Python 3.x
In Python 3, all strings are in Unicode, and there's a distinct type,
bytes, which serves to store non-Unicode versions of strings. How that
fits, I don't know.
I'd upgrade to Python 3.1, Python 3.0 has a lot of known problems.
But I think your real problem is:
the Pickler constructor expects a binary file, so you'll want "wb"
instead of "w" on the open().
With that change, it works for me:
Unpickling list.
['sweet', 'hot', 'dill']
['whole', 'spear', 'chip']
['Claussen', 'Heinz', 'Vlassic']
DaveA
More information about the Tutor
mailing list