python - 如何在 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')
推荐阅读
- android - 在公司内部提供 Android 应用程序
- apache-kafka - Debezium + Schema Registry Avro Schema:为什么我有“之前”和“之后”字段,以及如何将其与 HudiDeltaStreamer 一起使用?
- sql-server - SQL Server 嵌套游标和变量声明
- r - coxph 误差权重必须是有限的。我如何退回这个模型?
- python - 批量读取csv文件。阅读器总是错过同一行
- c# - AWS 中的 Windows 服务应用程序多可用区高可用性
- dataset - 有没有办法在没有翻译的情况下找到荷兰语电话交谈的语气/情绪?
- r - 如何创建一个新列,将值与来自不同数据框的标题匹配
- r - 更正数据框中的变量值,使用 R 中另一个数据框中的变量特定值应用函数
- javascript - 单击后更改颜色并停止功能(仅 JavaScript)