[英]How to match lines of text above and below a certain string up to another string - RegEx
[英]How to lookup string in text file and output specific lines above and below
我找不到针对特定问题的解决方案,所以我创建了一个新问题。 如何在文件中找到字符串,并从上方3行和下方25行输出? 我到目前为止拥有以下内容,但只能在比赛下方显示25。
with open("driveDetails.txt", "r") as f:
searchlines = f.readlines()
for i, line in enumerate(searchlines):
if "Failed" in line:
for l in searchlines[i:i+25]: print l,
print
break
以下是文件内容的示例。 我需要搜索“失败”,然后从3行开始打印(ID:0:1:6),然后从+ 25开始打印。我没有列出每条记录的所有行,所以我只列出了...
ID : 0:1:1
Status : Non-Critical
Name : Physical Disk 0:1:6
State : Online
Power Status : Spun Up
Bus Protocol : SAS
Media : HDD
Part of Cache Pool : Not Applicable
Remaining Rated Write Endurance : Not Applicable
Failure Predicted : Yes
Revision : ES66
Driver Version : Not Applicable
Model Number : Not Applicable
T10 PI Capable : No
Certified : Yes
Encryption Capable : No
Encrypted : Not Applicable
Progress : Not Applicable
Product ID : HDSG02032923
Serial No. : 7DK30358
...
ID : 0:1:6
Status : Non-Critical
Name : Physical Disk 0:1:6
State : Failed
Power Status : Spun Up
Bus Protocol : SAS
Media : HDD
Part of Cache Pool : Not Applicable
Remaining Rated Write Endurance : Not Applicable
Failure Predicted : Yes
Revision : ES66
Driver Version : Not Applicable
Model Number : Not Applicable
T10 PI Capable : No
Certified : Yes
Encryption Capable : No
Encrypted : Not Applicable
Progress : Not Applicable
Product ID : HDSG09393329
Serial No. : 7DK3035B
...
问题 :在文本文件中查找字符串并输出特定行
解决方案, 无需使用固定行数和dict
对象的indices
。
缺点 :您正在失去订单! 如果这是importand,请改用
OrderedDict
。
打开文件并循环浏览
with io.StringIO(DATA) as data_in: while True:
定义一个dict
并用n行读取一条记录 。
record = {} for _ in range(20): try: line = next(data_in).rstrip() except StopIteration: break
获取每行的key
, value
对,并将其分配给dict
。
key, value = line.split(' : ') record.setdefault(key.strip(' '), value.strip(' '))
验证结果record
。 如果键'State' == 'Failed'
请对该record
任何操作。
if not record: break elif 'State' in record: if record['State'] == 'Failed': print('{}'.format(record)) else: print('ERROR:{}'.format(record))
输出 :
{'Serial No.': '7DK3035B', 'State': 'Failed', 'ID': '0:1:6', ... (omitted for brevity)
使用Python测试:3.4.2
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.