关于 pickle的用法
import pickle as pimport os
class MyDes:
def __init__(self,data = 0, string = ''):
self.data = data
self.string = string
def __get__(self,instance,owner):
filename = 'C:/Users/user/Desktop/{0}.pkl'.format(self.string)
self.f=open(filename,'wb')
p.load(filename)
self.f.close()
return self.data
def __set__(self,instance,value):
filename = 'C:/Users/user/Desktop/{0}.pkl'.format(self.string)
self.f=open(filename,'wb')
self.data = value
p.dump(value, filename)
self.f.close()
def __delete__(self,instance):
filename = 'C:/Users/user/Desktop/{0}.pkl'.format(self.string)
os.remove(filename)
class Test:
x=MyDes('x')
y=MyDes('y')
代码是这样的,就是第46讲课后练习的最后一刻,
然后
test=Test()
test.x=10
然后这边一直报错,报错类型是
Traceback (most recent call last):
File "<pyshell#15>", line 1, in <module>
test.x=10
File "C:\Users\user\Desktop\新建文本文档.py", line 19, in __set__
p.dump(value, filename)
TypeError: file must have a 'write' attribute
我不理解的是,我已经把文件用‘wb’的方式打开了,为什么这个文件无法导入数据呢,有没有大佬解答一下的 Python的open和pickle应该不共用 qiuyouzhi 发表于 2020-4-18 14:40
Python的open和pickle应该不共用
def __set__(self, instance, value):
with open(self.filename, 'wb') as f:
pickle.dump(value, f)
MyDes.saved.append(self.name)
这是小甲鱼写的代码,这样写就不算open和pickle共用吗
雨谷 发表于 2020-4-18 15:29
def __set__(self, instance, value):
with open(self.filename, 'wb') as f:
pic ...
你倒是把文件对象传进dump的参数里啊 应该要传递文件对象给 dump(),而不是文件名:
def __set__(self,instance,value):
filename = 'C:/Users/user/Desktop/{0}.pkl'.format(self.string)
self.f=open(filename,'wb')
self.data = value
p.dump(value, self.f)
self.f.close() zltzlt 发表于 2020-4-18 17:23
应该要传递文件对象给 dump(),而不是文件名:
哦哦,原来问题在这里,多谢多谢
页:
[1]