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
我用一个示例脚本尝试了你的代码,如下所示
当我运行你的脚本时
^{pr2}$它打印出来了
如果这不是您想要的输出,请共享您正在使用的文件。在
下面是Python的方法。with语句将安全地打开文件,并在完成后处理关闭文件的操作。也可以使用“with”语句打开多个文件。How to open a file using the open with statement
相关问题 更多 >
编程相关推荐