如何打印文本文件中包含特定短语的每一行
我需要写一个函数,这个函数可以在一个文本文件里搜索某个短语,然后打印出每一行包含这个短语的内容。
def find_phrase(filename,phrase):
for line in open(filename):
if phrase in line:
print line,
这就是我目前的代码,但它只打印出第一次出现的内容。
2 个回答
0
下面是一个很简洁的Python写法。使用“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
1
我用一个示例脚本试了你的代码,内容是这样的:
#sample.py
import sys
print "testing sample"
sys.exit()
当我运行你的脚本时,
find_phrase('sample.py','sys')
它输出了:
import sys
sys.exit().
如果这不是你想要的结果,请分享一下你使用的文件。