Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
753 views
in Technique[技术] by (71.8m points)

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

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?

question from:https://stackoverflow.com/questions/25958824/python-pickle-gives-attributeerror-str-object-has-no-attribute-write

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

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)

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...