Okay just started teaching myself python recently and am on to pickling stuff. I just wrote a simple program exactly like the tutorial said (a few different ones actually) and I am getting an error. Here is my code:

import pickle

file = open('./text/pickle.txt','w')

list = ['one',2,'three',4,'five']

pickle.dump(list, file)

file.close

and here is the error I am getting:

Traceback (most recent call last):
  File "E:/python_sandbox/pickle.py", line 7, in <module>
    pickle.dump(list, 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

Please help. I can't seem to figure out where I am going wrong.

For one thing, don't name your list "list", as that's a reserved word in Python (try list('12345') ), same thing with file... But that modification won't help you.

I'm assuming you've got a new version of Python installed, as the method you're using will only work in earlier versions of python.

pickle.dump(obj, file[, protocol, *, fix_imports=True])ΒΆ

Write a pickled representation of obj to the open file object file. This is equivalent to Pickler(file, protocol).dump(obj).

The optional protocol argument tells the pickler to use the given protocol; supported protocols are 0, 1, 2, 3. The default protocol is 3; a backward-incompatible protocol designed for Python 3.0.

Specifying a negative protocol version selects the highest protocol version supported. The higher the protocol used, the more recent the version of Python needed to read the pickle produced.

The file argument must have a write() method that accepts a single bytes argument. It can thus be a file object opened for binary writing, a io.BytesIO instance, or any other custom object that meets this interface.

If fix_imports is True and protocol is less than 3, pickle will try to map the new Python 3.x names to the old module names used in Python 2.x, so that the pickle data stream is readable with Python 2.x.

That's from the 3.1 docs; note that you must open your files in binary mode now. So for dumping use 'wb', and loading use 'rb'.

thanks man... adding the 'b' to the open() command worked perfectly (and changing the list name... stupid mistake >_< )

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.