簡體   English   中英

如何在 Python 中打印包含某個字符串的文本文件的行?

[英]How to print the lines of a text file that contain a certain string in 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

以下是正確的解決方法:

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')

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM