Python处理CBL文件筛选非注释行后仅输出单行问题求助
问题排查与解决方案
问题根源
每次匹配到符合条件的行时,都用'w'模式打开输出文件——这个模式会清空文件原有内容并重新写入,所以最终每个文件只保留了最后一行符合条件的内容。此外代码还存在其他细节问题:全局变量冗余、文件未手动关闭、异常处理过于宽泛。
修复方案
- 将输出文件的打开操作移到行循环外部,避免重复打开清空文件
- 使用
with语句管理文件句柄,自动处理文件关闭,避免资源泄漏 - 移除不必要的全局变量,缩小变量作用域
- 增加行长度检查,防止短行导致索引越界错误
- 提前创建输出目录,避免因目录不存在写入失败
- 细化异常处理,输出具体错误信息便于定位问题
修复后的代码
from pathlib import Path import os input_dir = Path('C:\\Users\\user1\\Desktop\\Cobol/') output_dir = Path('C:\\Users\\user1\\Desktop\\TempCOBOL\\Updated') # 确保输出目录存在,不存在则创建 output_dir.mkdir(parents=True, exist_ok=True) def process_files_uncomment(inpfiles): for inpfile in inpfiles: writereccount = 0 output_path = output_dir / os.path.basename(inpfile) try: # 同时打开输入和输出文件,with语句自动管理关闭 with open(inpfile, 'r') as inp_handle, open(output_path, 'w') as out_handle: for line in inp_handle: # 跳过空行,避免后续索引检查报错 if not line.strip(): continue if line[0] == '\t': continue # 确保行长度足够,防止索引越界 if len(line) >= 7 and line[6] != '*': writereccount += 1 out_handle.write(line) print(f'Total number of UN-COMMENTED LINES for {inpfile.name}: {writereccount}') except Exception as e: print(f'Exception while processing {inpfile.name}: {str(e)}') process_files_uncomment(input_dir.glob('*.CBL'))
关键优化说明
- 输出文件在循环外以
'w'模式打开,一次性写入所有符合条件的行,避免重复清空 with语句自动处理文件关闭,无需手动调用close()- 增加
len(line)>=7检查,防止短行触发IndexError - 提前创建输出目录,避免因目录缺失导致写入失败
- 异常处理添加文件名和具体错误信息,便于快速定位问题
内容的提问来源于stack exchange,提问作者6708
相关产品推荐
相关产品推荐

