[Tutor] Incrementing a line?

Jim Boone jboone01 at bcuc.ac.uk
Wed Dec 10 04:49:00 EST 2003


Hejsan Magnus!

Thanks for that I'll look into it, I've got it working at the moment 
with Dons snippet of code, but I'll look into these other bits, it's 
literally been years since I've done any coding, and while I'm aware of 
what can be done, I can't recollect how to do things!  What you're 
saying makes sense, now I just have to 'own' it if you like.  Looks like 
a good list, probably would have helped to have joined earlier before 
writing the bulk of my little app!

Cheers,

Jim


Magnus Lycka wrote:

>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.)
>
>  
>


-- 
Jim Boone
--------------------------------------------
Buckinghamshire Chilterns University College
R&D Manager - Information and Communication Technologies
Tel: 01494 522141 ext 3569

The myth that Bill Gates has appeared like a knight in shining armor to lead all customers out of a mire of technological chaos neatly ignores the fact that it was he who, by peddling second-rate technology, led them into it in the first place, and continues to do so today.

~Douglas Adams~





More information about the Tutor mailing list