python pickle gives "AttributeError: 'str' object has no attribute 'write'"

Question:

When I try to pickle something, I get an AttributeError: 'str' object has no attribute 'write'

An example:

import pickle
pickle.dump({"a dict":True},"a-file.pickle")

produces:

...
AttributeError: 'str' object has no attribute 'write'

What’s wrong?

Asked By: drevicko

||

Answers:

It’s a trivial mistake: pickle.dump(obj,file) takes a file object, not a file name.

What I need is something like:

with open("a-file.pickle",'wb') as f:
    pickle.dump({"a dict":True},f)
Answered By: drevicko
Categories: questions Tags: , ,
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.