Python读取文件时匹配到指定单词后打印换行分隔的问题如何解决
问题根因
你当前的代码在检测到行包含location时,会先执行打印换行的逻辑,再输出该行本身,所以换行就出现在了location的前面。
调整后代码
with open('test.txt') as my_file: match = False for line in my_file: current_content = " ".join(line.split()) # 先处理匹配区间逻辑和行输出 if 'text1' in line: match = True print(current_content) elif 'text3' in line: match = False print(current_content) elif match: print(current_content) # 输出完当前行后判断是否是location行,是的话追加换行 if 'location' in line: print('\n')
改动说明
- 调换了
location判断和行输出的顺序,确保换行打在location行的后面 - 统一处理行内容的空格格式化,避免重复写
split和join逻辑
内容的提问来源于stack exchange,提问作者A Muamalat
相关产品推荐
相关产品推荐

