Iterate over text file, discarding some lines via context manager

fetchinson . fetchinson at
Fri Nov 28 16:04:30 CET 2014

Hi all,

I have a feeling that I should solve this by a context manager but
since I've never used them I'm not sure what the optimal (in the
python sense) solution is. So basically what I do all the time is

for line in open( 'myfile' ):
    if not line:
        # discard empty lines
    if line.startswith( '#' ):
        # discard lines starting with #
    items = line.split( )
    if not items:
        # discard lines with only spaces, tabs, etc

    process( items )

You see I'd like to ignore lines which are empty, start with a #, or
are only white space. How would I write a context manager so that the
above simply becomes

with some_tricky_stuff( 'myfile' ) as items:
    process( items )


Psss, psss, put it down! -

More information about the Python-list mailing list