批量处理TXT文件:合并重排最后三行的Python脚本问题排查
问题与修复方案
问题场景
目录E:\Desktop\Social_media\edit8\New folder下有大量TXT文件,示例内容如下:
Bolt 2,739,393 Classmates 1,267,092 SixDegrees 1,077,353 PlanetAll 552,488 theGlobe 437,847 OpenDiary 9,251 1998 MARCH 034+
需求是将每个文件最后三行合并为034+ MARCH 1998格式的单行,但现有Python脚本未生效。
原脚本问题排查
原脚本的核心逻辑仅交换了最后三行的位置:
lines[-1], lines[-2], lines[-3] = lines[-3], lines[-2], lines[-1]
这只是把年份(1998)和编号(034+)的位置互换,最终还是保留三行,没有完成合并操作,这是脚本未达到需求的根本原因。
修复后的脚本
import os directory_path = r'E:\Desktop\Social_media\edit8\New folder' def process_file(file_path): with open(file_path, 'r') as file: # 读取非空行并去除首尾空白 lines = [line.strip() for line in file.readlines() if line.strip()] # 确保文件至少有3行内容 if len(lines) >= 3: # 提取最后三行的内容 year, month, code = lines[-3], lines[-2], lines[-1] # 按要求格式合并成单行 merged_line = f"{code} {month} {year}" # 替换原最后三行为合并后的单行 lines = lines[:-3] + [merged_line] # 写入修改后的内容 with open(file_path, 'w') as file: file.write('\n'.join(lines)) # 遍历目录下所有TXT文件 for root, _, files in os.walk(directory_path): for filename in files: if filename.endswith('.txt'): file_path = os.path.join(root, filename) process_file(file_path) print(f'已处理:{filename}') print('所有文件处理完成!')
关键修复点
- 提取最后三行对应的值:年份(
lines[-3])、月份(lines[-2])、编号(lines[-1]) - 使用f-string将三个值合并为
编号 月份 年份格式的单行 - 删除原列表中的最后三行,替换为合并后的单行
- 将修改后的列表重新写入文件
内容的提问来源于stack exchange,提问作者Pubg Mobile
相关产品推荐
相关产品推荐

