python - 如何在文本文件中查找字符串并在上方和下方输出特定行
问题描述
我无法为我的特定问题找到解决方案,所以我正在创建一个新问题。如何在文件中找到一个字符串并从上面的 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
...
解决方案
问题:在文本文件中查找字符串并输出特定行
无需使用固定数量的行和对象 indices
的解决方案。dict
缺点:您正在失去订单!如果这很重要,请
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
。如果 key'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
推荐阅读
- java - 对包含数字和字母的字符串列表进行排序
- javascript - 不查找目录时未找到目录
- node.js - 上传到heroku后将前端连接到server.js的问题
- angular - 当用户在角度数据表中单击一行时如何展开/折叠一行?
- python - 使用 API discord.py 的随机猫生成器
- python - 如何从 numpy 数组中删除重叠块?
- vba - 设置时的 Range.Text 过滤器
- python - 如何以适当的方式更改我的工作目录?
- three.js - 如何使用三个js将物体放置在球面上
- performance - PowerShell:比较 2 个大型 CSV 文件以查找其中一个中不存在的用户