首页 > 解决方案 > 如何在 Python 中打印包含特定字符串的文本文件的行?

问题描述

rpm_list = ['201.abc.rpm', '202.xyz.rpm']
fh_file = open(text_file, 'r')
rpm_found = False
for rpm in rpm_list:
    for line in fh_file:
        if rpm in line:
            fh.write('\n\nSuccess: ' + rpm + ' was found in: ' + text_file + '\n\t at the following line: \n' + line)
            rpm_found = True
    if rpm_found == False:
        fh.write('\n\nError: ' + rpm + 'was not found in: ' + text_file + '\n')

如果在文本文件中找到字符串,那么我想打印如下内容:

Success: 201.abc.rpm was found in text_file at the following line:

line 26: abc abc 201.abc.rpm abc abc

Success: 202.xyz.rpm was found in text_file at the following line:

line 108: xyz xyz 202.xyz.rpm xyz xyz

我的代码只为第一个元素打印rpm_list两次。它不会打印第二个元素的消息。

此外,如果在文本文件中找不到字符串,我还想打印一条消息,例如:

Error: 201.abc.rpm was not found in the text_file

Error: 202.xyz.rpm was not found in the text_file

标签: pythonpython-2.7

解决方案


以下是正确的解决方案:

rpm_list = ['201.abc.rpm', '202.xyz.rpm']
fh_file = open(text_file, 'r')

for rpm in rpm_list:
    rpm_found = False
    for line in fh_file:
        if rpm in line:
            fh.write('\n\nSuccess: ' + rpm + ' was found in: ' + text_file + '\n\t at the following line: \n' + line)
            rpm_found = True
    fh_file.seek(0)
    if rpm_found == False:
        fh.write('\n\nError: ' + rpm + 'was not found in: ' + text_file + '\n')

推荐阅读