Search a text file and print related lines in Python?

后端 未结 3 1367
长情又很酷
长情又很酷 2020-11-29 21:56

How do I search a text file for a key-phrase or keyword and then print the line that key-phrase or keyword is in?

3条回答
  •  情话喂你
    2020-11-29 22:28

    Note the potential for an out-of-range index with "i+3". You could do something like:

    with open("file.txt", "r") as f:
        searchlines = f.readlines()
    j=len(searchlines)-1
    for i, line in enumerate(searchlines):
        if "searchphrase" in line: 
            k=min(i+3,j)
            for l in searchlines[i:k]: print l,
            print
    

    Edit: maybe not necessary. I just tested some examples. x[y] will give errors if y is out of range, but x[y:z] doesn't seem to give errors for out of range values of y and z.

提交回复
热议问题