import json
class ReadWriteBase:
def __init__(self, filename):
self.filename = filename
def set_filename(self, filename):
self.filename = filename
def get_filename(self):
return self.filename
def read(self):
try:
with open(self.filename, 'r') as fr:
data = fr.readlines()
return data
except Exception as e:
print(f"e: {e}")
return None
def write(self, data):
try:
with open(self.filename, 'w') as fw:
fw.write(data)
except Exception as e:
print(f"e: {e}")
return False
return True
class JsonReadWrite(ReadWriteBase):
"""json文件的load和dump"""
def __init__(self, filename):
super().__init__(filename)
def read(self):
try:
with open(self.filename, 'r') as fr:
data = json.load(fr)
except Exception as e:
print(f"load出错:{e}")
return None
return data
def write(self, data):
try:
with open(self.filename, 'w') as fw:
json.dump(data, fw)
except Exception as e:
print(f"dump出错:{e}")
return False
return True
class BinaryReadWrite(ReadWriteBase):
"""二进制文件的read和write"""
def __init__(self, filename):
super().__init__(filename)
def read(self):
try:
with open(self.filename, 'rb') as fr:
data = fr.readlines()
return data
except Exception as e:
print(f"e: {e}")
return None
def write(self, data):
try:
# if not self.filename.endswith(".lic"):
# self.filename += ".lic"
with open(self.filename, 'wb') as fw:
fw.write(data)
except Exception as e:
print(f"e: {e}")
return False
return True
class ReadWriteInterface:
def __init__(self, file_obj):
self.file_obj = file_obj
def read(self):
data = self.file_obj.read()
return data
def write(self, data):
ret = self.file_obj.write(data)
return ret
def main():
filename = "../res/a.lic"
lic_obj = ReadWriteBase(filename)
filerw_obj = ReadWriteInterface(lic_obj)
ret = filerw_obj.write("abcdefg")
print(f"ret: {ret}")
if __name__ == '__main__':
main()
文件读取与保存(面向对象练习)
最新推荐文章于 2024-10-28 11:00:05 发布