[英]How to print every line from a text file that contains a certain phrase
我必须编写一个函数,该函数可以在txt文件中搜索短语,然后打印包含该短语的每一行。
def find_phrase(filename,phrase):
for line in open(filename):
if phrase in line:
print line,
这就是我目前所拥有的,它只打印第一个实例。
我已经用示例脚本尝试了您的代码,就像这样
#sample.py
import sys
print "testing sample"
sys.exit()
当我运行您的脚本时,
find_phrase('sample.py','sys')
它打印,
import sys
sys.exit().
如果这不是您想要的输出,请共享您正在使用的文件。
以下是pythonic方法。 with语句将安全地打开文件并在完成后处理关闭文件。 您也可以使用“ with”语句打开多个文件。 如何使用open with语句打开文件
def print_found_lines(filename, phrase):
"""Print the lines in the file that contains the given phrase."""
with open(filename, "r") as file:
for line in file:
if phrase in line:
print(line.replace("\n", ""))
# end with (closes file automatically)
# end print_found_lines
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.