5

I'm trying to put a method in one of my classes which will allow me to pickle and unpickle files. So for example, I have

import pickle

class SomeClass:

    def otherMethods:
        pass

    def save_to_file(self, filename, file_to_save):
        with (filename,'wb') as output:
            pickle.dump(file_to_save,output,pickle.HIGHEST_PROTOCOL)
        print("Data has been saved.")

Now, when I create an instance of this 'SomeClass', I expect to be able to call as follows from the terminal...

myfile = [1,2,3] # or anything else
SomeClass.save_to_file('myfile.pk',myfile)

However, what gets thrown is an:

'AttributeError: __exit__'

I've seen a few different posts of people having difficulties with similar use cases, but I haven't been able to figure out how they apply in my situation. Help would be much appreciated.

4
  • did you call SomeClass.save_to_file or SomeClassObj.save_to_file? Commented Jun 7, 2013 at 5:22
  • I created an instance of SomeClass... i.e a = SomeClass(), then a.save_to_file(...) Commented Jun 7, 2013 at 5:23
  • maybe simplify the 'with' statement Commented Jun 7, 2013 at 5:24
  • @donfede how can I simplify the 'with' statement? Commented Jun 7, 2013 at 5:25

1 Answer 1

11

open is missing:

with open(filename,'wb') as output:

The with statement expects a context manager with __enter__ and __exit__ methods, and raises AttributeError because the tuple (filename,'wb') does not have them.

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.