经常做文本处理,会写大量的 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()

版权声明:本文为renyuanfang原创文章,遵循 CC 4.0 BY-SA 版权协议,转载请附上原文出处链接和本声明。
原文链接:https://blog.csdn.net/renyuanfang/article/details/126995710