Python3实现:查找含;;;的文本行,合并下一行并调整注释位置
Python3 文本文件合并处理实现
需求说明
处理文本文件中的特定行:
- 定位包含
;;;的行 - 移除该行中
;;;及其后续内容,将下一行内容合并到该行原;;;的位置 - 把原
;;;及注释内容移到合并后行的末尾
实现代码
def process_text_file(input_file, output_file): # 读取文件,保留每行原始空白,仅去除换行符 with open(input_file, 'r', encoding='utf-8') as infile: lines = [line.rstrip('\n') for line in infile] processed_content = [] index = 0 total_lines = len(lines) while index < total_lines: current_line = lines[index] if ';;;' in current_line: # 拆分内容与注释部分 content_before, comment_rest = current_line.split(';;;', 1) full_comment = f';;;{comment_rest}' # 合并当前行内容与下一行 if index + 1 < total_lines: next_line = lines[index + 1] merged_line = f"{content_before}{next_line} {full_comment}" processed_content.append(merged_line) index += 2 continue # 无需合并的行直接加入结果 processed_content.append(current_line) index += 1 # 写入处理后的文件 with open(output_file, 'w', encoding='utf-8') as outfile: outfile.write('\n'.join(processed_content)) # 调用示例:处理原文件output.txt,输出到processed_output.txt process_text_file('output.txt', 'processed_output.txt')
代码说明
- 格式保留:用
rstrip('\n')仅移除换行符,保留每行的原始空格与缩进 - 精准拆分:
split(';;;', 1)只拆分首次出现的;;;,避免注释内部包含该标记时出错 - 循环控制:合并完成后直接跳过下一行,防止重复处理
- 输出对齐:合并时添加固定空格分隔内容与注释,匹配示例格式(可根据需求调整空格数量)
测试效果
原始文件内容:
0 ;;; test comment 10.20.20.111 0B:0A:61:48:70:20 s2.... lan waiting
处理后文件内容:
0 10.20.20.111 0B:0A:61:48:70:20 s2.... lan waiting ;;; test comment
内容的提问来源于stack exchange,提问作者Aleksa Markovic
相关产品推荐
相关产品推荐

