views:

123

answers:

1

This is in reference to a question I posted yesterday http://stackoverflow.com/questions/1925284/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.

+2  A: 

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()
ghostdog74
I like it. It's easier than the one I was thinking of using deque. You do need a minor change to handle if the match is in the first few lines of the file (n<context), and Jessica didn't specify how to handle cases where search exists not just in the matched line but also in one of the lines within context after that line.
Andrew Dalke