script files with python (instead of tcsh/bash)?

Peter Otten __peter__ at web.de
Wed Mar 25 08:27:46 EDT 2009


Esmail wrote:

> Hello David,
> 
> R. David Murray wrote:
>> Esmail <ebonak at hotmail.com> wrote:
>> 
>> Here's a more Pythonic way to do that:
>> 
>>     with open('somefile') as f:
>>         for line in f:
>>             if 'somestring' in line:
>>                 #do something
>> 
>> In other words, you don't have to read the lines into a list first if all
>> you are going to do is iterate through them.
> 
> Cool .. stored away for future reference.
> 
> In this case I believe I needed the contents in a list because the line
> I was looking for was above one that I could easily identify. Ie, once
> I had the index, I could go back/up one index to find the line I needed
> to process.

Here's one way to avoid the list:

last_line = None
for line in f:
    if "somestring" in line and last_line is not None:
         # do something with last_line
    last_line = line

Peter




More information about the Python-list mailing list