文件读取与保存(面向对象练习)

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()

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值