views:

60

answers:

2

Hi there, Im trying to search a file where the the line containing the search term is found and printed along with a number of lines before and after the search term defined by the user. The coding i have so far is:

f = open(f, 'r')
d = {}
for n, line in enumerate(f):
    d[n%numb] = line.rstrip()
    if search_term in line:
        for i in rang(n+1,n+1+numb):
            print d[i%numb]
        for i in range(1, numb):
            print f.next().rstrip()

But i get a TypeError at d[%numb] = line.rstrip() Unsupported operand type(s) for %: 'int' and 'str'

Help would be great thanks

+1  A: 

You haven't specified what numb is, but I'm guessing it's something like:

numb = sys.argv[1]

The sys.argv is an array of strings, rather than integers. Try converting the string to an integer:

numb = int(sys.argv[1])
Greg Hewgill
A: 

n % numb can have different meanings, depending on the type of n and numb. If they are both numbers it means "take the modulus" which I presume is what you intend. If n is a string then it means do % formatting. If n is a number and numb is a string Python does not know what to do and raises a TypeError. Did you look at the error message on the exception? It should say "unsupported operand type(s) for %: 'int' and 'str'", which will tell you everything you need to know.

Once you fix that, I don't think your program will do what you want - there are several problems with it. 1) if your search term is in the first numb lines then you will get an exception trying to read lines out of the dictionary that have not been inserted yet.

2) the last loop in your code reads the next numb lines but does not search them, so any occurrences of the search term will be missed.

3) Using modulus to maintain the buffer of lines is clever, but there is a better way. Look at the collections.deque class,

Dave Kirby