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.
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.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.