Python 高效文件读写与上下文管理器 with 语句实战

一、安全读写超大文件

def process_large_file(filepath: str):
    with open(filepath, 'r', encoding='utf-8') as f:
        for line in f: # 惰性按行流式迭代,避免内存爆满
            if 'ERROR' in line:
                yield line.strip()