使用python 装饰器写 IO

经常做文本处理,会写大量的 with open(file,... encoding="utf-8") as f ,可以使用装饰器来写一个一劳永逸的IO方式,每次代码只需要写业务处理逻辑,而且能够 自己不断优化,减少重复代码的开发。

class Writer(object):
    """写文件"""
    def __init__(self,outfile="out.log",mode="debug"):
        self.outfile = outfile
        self.mode = mode
        print(f"filename:{self.outfile}; mode:{mode}")

    def __call__(self, line_func):
        @wraps(line_func)
        def wrapped_function(*args,**kwargs):
            # 检查 目录是否存在
            if not Path(self.outfile).parent.is_dir():
                Path(self.outfile).parent.mkdir(parents=True, exist_ok=False)
            with open(self.outfile,'w',encoding="utf-8") as fw:
                for i,line in enumerate(line_func(*args,**kwargs)):
                    fw.write(f"{line}\n")
                    if self.mode == "debug" and i % 10000 == 0:
                        print(f"write {i} lines")
                    if self.mode == "test" and i > 100:
                        break
                print(f"[{self.mode}]: {self.outfile} writer finish total {i} lines")

        return wrapped_function


if __name__ == "__main__":
    @Writer(outfile="test/outlog.txt", mode="test")
    def hello_word():
        for i in range(1000):
            yield i


    hello_word()

评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值