开发者

How do I write a write() method in a pkl file that I can use in my python scrpits?

I am trying a share a boolean between different scripts. In one script, I want to edit the boolean if a certain function is called. In the other scripts, I want to use the boolean. I'm trying to use pickling, but I'm in way over my head. I have no idea what to write in my pkl file. My code kinda looks like this:

one.py

    import pickle

    boolean = False
    pickle.dumps(boolean, "filename.pkl")

    class Foo(object):

    #init method irrelevant

        def bar(self):
            foobar = raw_input("> ")

            if foobar == "baz":
                boolean = True
                pkl_file = open("filename.pkl", 'w')
                pickle.dumps(boolean, "filename.pkl")
            else:
                print "Hello"

two.py

    import pickle

    class Foobar(object):

    #init method irrelevant

    def foo_bar(self):
        foobar = raw_input("> ")
        boolean = pickle.loads("filename.pkl")

        if foobar == "foo" and boolean:
            print "Hi!"
        elif foobar == "foo":
            print "Hello there."
        else:
            print "Bye!"

I have another script that does something similar to two开发者_如何学JAVA.py. My pkl file is empty.

When I try to run the main script (a completely different one from the ones with pickling), I get "AttributeError: 'str' object has no attribute 'write'


The arguments required for dump and load need a file object, so you cannot simply pass the filename as a string. (and you should use the non-s version as mentioned by other answers)

Try something like this: pickle.dump(boolean, open("filename.pkl", "w"))

and boolean = pickle.load(open("filename.pkl", "r"))


First off, you need to use pickle.dump(...) and pickle.load(), not the string versions, like so,

import pickle

f = open('gherkin.pkl','w')
pickle.dump(False,f)
f.close()
g = open('gherkin.pkl','r')
print pickle.load(g)
g.close()

Secondly, if you open the file a second time to read it you need to set the mode to "r", otherwise you're going to destroy it.


You're using the wrong API. The dumps and loads methods you are using are for strings, not files. (The s in the name stands for string). According to the documentation you should be using dump and load with a file object. You should previously open the file object.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜