![](/img/trans.png)
[英]I am trying to write python script to find a string in file with more than 1000 lines and delete few lines (10) after that string match
[英]Copy few lines before and after the match string in python
我是python的新手,嘗試編寫一個腳本,在找到匹配的字符串之前復制5行,然后復制5行
import re
text_file = open(input("Input-file name : ") , "r")
fi = text_file.readlines()
test = re.compile(r'matching character')
for i in range (len(fi)):
if test.search(fi[i]):
print(fi[max(0, i-5)])
print(fi[max(0, i-4)])
print(fi[max(0, i-3)])
print(fi[max(0, i-2)])
print(fi[max(0, i-1)])
print(fi[max(0, i-0)])
print(fi[max(0, i+1)])
print(fi[max(0, i+2)])
print(fi[max(0, i+3)])
print(fi[max(0, i+4)])
有沒有比添加多個print語句在一個命令中獲得輸出更好的方法。
假定匹配的行包含在“之后”的5行中,則:
block = fi[max(0, i - 5): min(len(fi), i + 5)]
將為您提供行列表。 要將列表打印為一個塊,您可以執行以下操作:
print(''.join(block))
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.