|
马上注册,结交更多好友,享用更多功能^_^
您需要 登录 才可以下载或查看,没有账号?立即注册
x
import pickle as p
import os
class MyDes:
def __init__(self,attr):
self.attr = attr
pickle_file = open(('D:\\python代码库\\属性值\\%s.pkl'% self.attr),'a')
p.dump(self.attr,pickle_file)
pickle_file.close()
def __get__(self,instance):
return self.attr
def __set__(self,instance,value):
self.attr = value
with open(('D:\\python代码库\\属性值\\%s.pkl' % self.attr), 'a') as pickle_file:
p.dump(self.attr, pickle_file)
def __delete___(self,instance):
os.remove('D:\\python代码\\属性值\\%s.pkl' % self.attr)
del self.attr
class Test:
x = MyDes('x')
y = MyDes('y')
为什么会报错,我没有找到问题所在
Traceback (most recent call last):
File "D:/python代码库/pickle_MyDes.py", line 24, in <module>
class Test:
File "D:/python代码库/pickle_MyDes.py", line 25, in Test
x = MyDes('x')
File "D:/python代码库/pickle_MyDes.py", line 9, in __init__
p.dump(self.attr,pickle_file)
TypeError: write() argument must be str, not bytes
Process finished with exit code 1
用 pickle 模块写入文件是 二进制写入的,你需要在打开文件时候加上 'b' 表示以二进制形式打开文件
对于你这里的代码,在 open 那 'a' 改成 'ab' 应该避免这个报错
|
|