首页 > 解决方案 > 如何在文本文件中查找字符串并在上方和下方输出特定行

问题描述

我无法为我的特定问题找到解决方案,所以我正在创建一个新问题。如何在文件中找到一个字符串并从上面的 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
... 

标签: pythonsearchprinting

解决方案


问题:在文本文件中查找字符串并输出特定行

无需使用固定数量的行和对象 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


推荐阅读