【发布时间】:2023-03-13 20:11:02
【问题描述】:
我正在搜索一个文本文件,并且想要复制并写入与另一个文本文件中的匹配项相关联的行块。找到搜索条件后,我想将前一行和后 9 行(共 10 行)复制/写出到每个匹配的文件中。
要搜索的示例输入文件
Line 1: File sent to xyz blah blah:
Line 2: Search Criteria here
Line 3
Line 4
Line 5
Line 6
Line 7
Line 8
Line 9
Line 10
Line 1: File sent to xyz blah blah:
Line 2: Search Criteria here
Line 3
Line 4
Line 5
Line 6
Line 7
Line 8
Line 9
Line 10
我已经开始的代码:
searchList = []
searchStr = "Search Criteria here"
with open('', 'rt') as fInput:
previous = next(fInput)
for line in fInput:
if line.find(searchStr) != -1:
searchList.append(previous)
searchList.append(line.lstrip('\n'))
with open('Output.txt','a') as fOutput:
OutPut.write("\n".join(searchList))
上面的代码保存到这样的文件中,第一行和第二行之间有空格:
mm/dd/yyy hh:mm:ss.MMM File sent to xyz:
Line 2: Search Criteria here
mm/dd/yyy hh:mm:ss.MMM File sent to xyz:
Line 2: Search Criteria here
我想保存所有 10 行,就像它们在输入文件中一样。
【问题讨论】:
标签: python python-3.x python-textprocessing