如何用Python将TXT文件中每4行合并为一行?
Python实现每4行文本合并为一行
下面是直接可用的代码,能完成你需要的每4行合并为一行的需求:
# 替换为你的输入文件路径和输出文件路径 input_path = "your_input.txt" output_path = "your_output.txt" with open(input_path, 'r', encoding='utf-8') as in_file, open(output_path, 'w', encoding='utf-8') as out_file: # 读取所有行,过滤空行并去除每行首尾的换行、空格 processed_lines = [line.strip() for line in in_file if line.strip()] # 按每4行一组进行合并 for idx in range(0, len(processed_lines), 4): # 取出当前组的行(最后一组不足4行也会处理) current_group = processed_lines[idx:idx+4] # 将组内的行用空格拼接成一行,写入输出文件 merged_line = ' '.join(current_group) out_file.write(f"{merged_line}\n")
代码说明:
strip():去除每行首尾的换行符、空格,避免合并后出现多余的空白。range(0, len(processed_lines), 4):通过步长4实现每4行一组的分组逻辑。' '.join(current_group):把组内的每行内容用空格连接成一行,保持原数据的分隔格式。- 支持处理文件末尾不足4行的情况,会自动将剩余行合并为最后一行。
使用时只需要把input_path和output_path替换成你实际的文件路径即可。
内容的提问来源于stack exchange,提问作者Peclet
相关产品推荐
相关产品推荐

