搜索文本文件并在Python中打印相关的行?

Noa*_*h R 32 python search file

如何在文本文件中搜索关键短语或关键字,然后打印关键短语或关键字所在的行?

sen*_*rle 58

searchfile = open("file.txt", "r")
for line in searchfile:
    if "searchphrase" in line: print line
searchfile.close()
Run Code Online (Sandbox Code Playgroud)

打印多行(以简单的方式)

f = open("file.txt", "r")
searchlines = f.readlines()
f.close()
for i, line in enumerate(searchlines):
    if "searchphrase" in line: 
        for l in searchlines[i:i+3]: print l,
        print
Run Code Online (Sandbox Code Playgroud)

逗号print l,可以防止额外的空格出现在输出中; 尾随打印语句划分不同行的结果.

或者更好(从Mark Ransom手中抢回):

with open("file.txt", "r") as f:
    searchlines = f.readlines()
for i, line in enumerate(searchlines):
    if "searchphrase" in line: 
        for l in searchlines[i:i+3]: print l,
        print
Run Code Online (Sandbox Code Playgroud)

  • 处理后关闭文件. (2认同)
  • 我该如何打印该线以及下面的其他三条线? (2认同)

Mar*_*som 21

with open('file.txt', 'r') as searchfile:
    for line in searchfile:
        if 'searchphrase' in line:
            print line
Run Code Online (Sandbox Code Playgroud)

向我肆无忌惮地复制的发送者道歉.

  • 尼斯.对于其他只是绊脚的人,此方法会自动关闭文件.在effbot.org上有一个很好的解释:[理解Python的"with"语句](http://effbot.org/zone/python-with-statement.htm) (4认同)
  • @senderle,谢谢你.我认为只是编辑你的答案,但我认为这会更烦人 - 而且`with`语句是Python最近的一个补充,使你的答案最适合某些人.你很久以前得到了我的+1! (3认同)
  • +1.我很生气 - 但后来我花了一点时间来理解这句话.这很棒! (2认同)