Python如何基于指定条件合并txt文件中的当前行与上一行?
Python 实现按规则合并文本行
实现规则:若当前行内容不以[开头,则将该行与上一行合并。
完整实现代码
# 定义输入输出文件路径 input_path = "input.txt" output_path = "output.txt" # 存储处理后的行 merged_lines = [] # 读取输入文件 with open(input_path, "r", encoding="utf-8") as f: for line in f: # 去掉行尾的换行符,保留其他格式字符 stripped_line = line.rstrip("\n") if not merged_lines: # 第一行直接加入 merged_lines.append(stripped_line) else: if stripped_line.startswith("["): # 以[开头,作为新行添加 merged_lines.append(stripped_line) else: # 不以[开头,拼接到上一行末尾 merged_lines[-1] += stripped_line # 写入输出文件 with open(output_path, "w", encoding="utf-8") as f: f.write("\n".join(merged_lines))
代码说明
- 替换代码中的
input.txt和output.txt为你实际的输入、输出文件路径即可直接运行 - 处理过程中仅会按照规则合并行,不会修改原有文本的其他内容
- 若需要处理GBK等其他编码的文件,修改
open方法中的encoding参数对应值即可 - 针对超大文件的优化版本(避免一次性加载全量内容到内存):
with open("input.txt", "r", encoding="utf-8") as in_f, open("output.txt", "w", encoding="utf-8") as out_f: # 暂存上一行的内容 prev_line = "" for line in in_f: stripped_line = line.rstrip("\n") if not prev_line: prev_line = stripped_line continue if stripped_line.startswith("["): # 当前行是新行,先写出上一行 out_f.write(prev_line + "\n") prev_line = stripped_line else: # 合并到上一行 prev_line += stripped_line # 写出最后一行 if prev_line: out_f.write(prev_line)
内容的提问来源于stack exchange,提问作者Jatin Chaturvedi
相关产品推荐
相关产品推荐

