Python:搜索文本文件并将包含前一行的行块写入另一个文件
我正在搜索一个文本文件,想在另一个文本文件中复制并写入与匹配项关联的行块。找到搜索条件后,我想将前一行和后9行(总共10行)复制/写出到每个匹配的文件中 要搜索的示例输入文件Python:搜索文本文件并将包含前一行的行块写入另一个文件,python,python-3.x,python-textprocessing,Python,Python 3.x,Python Textprocessing,我正在搜索一个文本文件,想在另一个文本文件中复制并写入与匹配项关联的行块。找到搜索条件后,我想将前一行和后9行(总共10行)复制/写出到每个匹配的文件中 要搜索的示例输入文件 Line 1: File sent to xyz blah blah: Line 2: Search Criteria here Line 3 Lin
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行,与输入文件中的完全相同。首先,读取文件并找到匹配的行号。记录行号,以便以后使用
all_lines = []
match_lines = []
with open('in_file.txt', 'r') as fInput:
for number, line in enumerate(fInput):
all_lines.append(line)
if searchStr in line:
match_lines.append(number)
然后,在匹配行
列表上循环,并从所有行
输出您关心的行:
num_lines_before = 1
num_lines_after = 10
with open('out_file.txt', 'w') as fOutput:
for line_number in match_lines:
# Get a slice containing the lines to write out
output_lines = all_lines[line_number-num_lines_before:line_number+num_lines_after+1]
fOutput.writelines(output_lines)
为了测试这一点,我将创建一个io.StringIO
对象来读/写一个字符串作为文件,并要求在前面一行,后面两行:
import io
strIn = """This is some text
12345
2 searchforthis
34567
45678
5 searchforthis
63r23tf
7pr9e2380
89spver894
949erc8m9
100948rm42"""
all_lines = []
match_lines = []
searchStr = "searchforthis"
# with open('in_file.txt', 'r') as fInput:
with io.StringIO(strIn) as fInput:
for number, line in enumerate(fInput):
all_lines.append(line)
if searchStr in line:
match_lines.append(number)
num_lines_before = 1
num_lines_after = 2
# with open('out_file.txt', 'w') as fOutput:
with io.StringIO("") as fOutput:
for line_number in match_lines:
# Get a slice containing the lines to write out
output_lines = all_lines[line_number-num_lines_before:line_number+num_lines_after+1]
fOutput.writelines(output_lines)
fOutput.write("----------\n") # Just to distinguish matches when we test
fOutput.seek(0)
print(fOutput.read())
给出此输出:
12345
2.这方面的研究
34567
45678
----------
45678
5.这方面的搜索
63r23tf
7pr9e2380
----------
谢谢@pranav hosangadi。我有最新的要求。我仍然希望将整个文本块写入一个文本文件,但也希望将每一行解析为一个.csv文件,以便在excel中打开。你推荐什么?@DChase我不知道你的意思。每一行是否已经包含在CSV中有意义的数据?我建议使用的writerow()
方法,但我确实需要更多信息来提出有意义的建议。如果您在使用csv.writer时遇到问题,并且无法解决,请随时发布另一个包含详细信息的问题。如果你在这里分享这个链接,我很乐意回答。我会尝试一下,如果我还有问题,我会告诉你。非常感谢。