Python按标记字符串分割文件至三个列表并导出文件的问题
按标记分割文件内容并导出为独立文件的解决方案
我是Python新手,现需将输入文件按标记字符串分割为Program info(programdef)、Program core(core)、Toollist(toollist)三部分,分别存入对应列表后导出为独立文件。目前仅能实现第一部分的匹配写入,不知如何从找到的标记处继续循环处理后续内容,或如何提取两个标记间的内容存入对应列表,恳请帮助。附当前代码:
import os filename = "D327971_fc1.i" # current program name file = open(filename, 'r') # read current program if os.stat(filename).st_size == 0: # check if size of file is null print('File is empty') file.close() else: read = file.readlines() programdef = [] toollist = [] core = [] line_num = -1 for line in read: start_line_point = "Zacatek" in line end_line_point = "Konec" in line toollist_point = "nastroj" in line programdef.append(line.strip()) if start_line_point: break core.append(line.strip()) if end_line_point: toollist.append(line.strip()) with open('0progdef.txt', 'w') as f: f.write(str(programdef)) with open('1core.txt', 'w') as f: f.write(str(core)) with open('2toollist.txt', 'w') as f: f.write(str(toollist))
问题分析
原代码的核心问题是缺少状态切换逻辑:用break直接终止循环会导致后续内容无法处理,且没有明确当前应该往哪个列表写入内容,导致各部分的append逻辑混乱。
修正后的代码
import os filename = "D327971_fc1.i" programdef = [] core = [] toollist = [] # 检查文件是否为空 if os.stat(filename).st_size == 0: print('File is empty') else: # 用with语句自动管理文件关闭,避免资源泄漏 with open(filename, 'r') as file: # 初始化当前要写入的目标列表 current_target = programdef for line in file: stripped_line = line.strip() # 根据标记切换目标列表 if "Zacatek" in stripped_line: current_target = core # 若不想将标记行加入core,可注释下面这行 current_target.append(stripped_line) continue if "Konec" in stripped_line: current_target = toollist # 若不想将标记行加入toollist,可注释下面这行 current_target.append(stripped_line) continue # 将当前行写入对应列表 current_target.append(stripped_line) # 写入独立文件,用换行符连接内容,生成易读的文本格式 with open('0progdef.txt', 'w') as f: f.write('\n'.join(programdef)) with open('1core.txt', 'w') as f: f.write('\n'.join(core)) with open('2toollist.txt', 'w') as f: f.write('\n'.join(toollist))
关键修改说明
- 状态变量控制:用
current_target变量跟踪当前应该写入的列表,遇到标记时切换目标,实现全文件遍历处理 - 文件安全处理:使用
with语句操作文件,自动完成关闭操作,避免手动关闭遗漏导致的资源问题 - 输出格式优化:用
'\n'.join()替代str(list),生成的文件每行对应原文件的一行内容,而非列表的字符串表示 - 灵活配置:可通过注释标记行的append代码,选择是否将分割标记包含到对应部分中
内容的提问来源于stack exchange,提问作者Petr Pyro
相关产品推荐
相关产品推荐

