如何从包含特定短语的文本文件中打印每一行

2024-04-27 00:48:31 发布

您现在位置:Python中文网/ 问答频道 /正文

我必须写一个函数,可以搜索一个文本文件的短语,然后打印每一行包含该短语。在

def find_phrase(filename,phrase):
    for line in open(filename):
        if phrase in line: 
            print line,

这就是我目前所拥有的,它只打印第一个实例。在


Tags: 实例函数inforifdeflineopen
2条回答

我用一个示例脚本尝试了你的代码,如下所示

#sample.py

import sys
print "testing sample"
sys.exit() 

当我运行你的脚本时

^{pr2}$

它打印出来了

import sys
sys.exit(). 

如果这不是您想要的输出,请共享您正在使用的文件。在

下面是Python的方法。with语句将安全地打开文件,并在完成后处理关闭文件的操作。也可以使用“with”语句打开多个文件。How to open a file using the open with statement

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

相关问题 更多 >