Searching a file

2019-09-03 03:03发布

This is in reference to a question I posted yesterday Searching a file in 3 different ways

I just require help now on two things, searching a file and and printing the line a search result is found on and all the lines after it to the end of the file.

Lastly i need help on coding were i search a file and print the line a search result is found on and a number of lines before and after the the search result. The number of lines printed before and after the search result is defined by the user and is the before/after amount of lines are the same.

1条回答
劳资没心,怎么记你
2楼-- · 2019-09-03 03:13

for the first part

for line in open("file"):
    line=line.rstrip()
    if "search" in line:
        f=1
    if f: print line

for the second part

context=3
search="myword"
f=open("file")
d={}
for n,line in enumerate(f):
    d[n%context]=line.rstrip()
    if search in line:
        for i in range(n+1,n+1+context):
            print d[i%context]
        for i in range(1,context):
            print f.next().rstrip()
f.close()
查看更多
登录 后发表回答