Re: [Tutor] Incrementing a line?

Magnus Lycka magnus at thinkware.se
Tue Dec 9 12:03:25 EST 2003


Hi Jim!

Jim Boone wrote:
> Howdy all, i hope this is the right list for my query, pythons a bit new 
> to me, and I'm trying dto something that I can't figure out:

You have come to the right place!
 
> for s in userlog.readlines():
>             for word in s.split():
>                 if word == ("19(Constraint"):
>                     constraintlog.write(s + "\n")
>                     print "\n\n*****Constraint Violations exist!!*****\n\n"
>         constraintlog.close()
> 
> Is a section of code i have, it reads a log file and cranks out a log 
> file on a certain condition, I can get it to write out the same line 
> which is in the original log file, which is useful, but, what would be 
> much more useful is if i could write out the line thats 10 lines after 
> the "19(Constraint", because it's more pertinent, but of course s+10 is 
> stupidly wrong.

In recent Python versions, there is a nice thingie called "enumerate()"
which will turn something like ['a', 'b', 'c'] into [(0,'a'), (1,'b'), 
(2,'c')] That's helpful here, right? In addition to this, you should 
assign the result of userlog.readlines() (which is a list object) to a 
variable name, so that you can access the element 10 steps further down, 
just as easily as the current element, right?

You just change your code to something like...

lines = userlog.readlines()
for i, s in lines:
    ...
        if ...
            ...
            print lines[i+10]

Note that this might cause an IndexError if lines don't extend that
far. (You can handle that with "if len(lines) > i+10:", or with
try/except.)

-- 
Magnus Lycka, Thinkware AB
Alvans vag 99, SE-907 50 UMEA, SWEDEN
phone: int+46 70 582 80 65, fax: int+46 70 612 80 65
http://www.thinkware.se/  mailto:magnus at thinkware.se



More information about the Tutor mailing list