我需要类似的东西,但是我不需要打印所有行,我只需要几行,直到每次出现的某个停止条件(如果您想打印/获取所有行,直到EOF设置none end条件:def find_occurences(file1_path, catch_start, catch_end):
results = []
with open(file1_path, 'r') as f1:
lines = f1.readlines()
i = 0
while i < len(lines):
if catch_start in lines[i]:
for j in range(i + 1, len(lines)):
if catch_end in lines[j] or j == len(lines)-1:
results.append(lines[i:j])
i = j
break
else:
i += 1
return results
然后,如果要将它们打印或写入另一个文件,则在一个列表中有作为列表出现的项,您可以将其分解,或者在调用函数中使用它。for result in find_occurrences(path, start_c, end_c):
for line in result:
print str(line)
with open(file_path, 'a') as f:
f.write(str(line))
另外,如果您是按行写入文件,则可能需要使用“a”而不是“w”,因为“w”将替换任何现有的文件内容。