Groups | Search | Server Info | Keyboard shortcuts | Login | Register [http] [https] [nntp] [nntps]


Groups > comp.lang.python > #81683

Iterate over text file, discarding some lines via context manager

Date 2014-11-28 16:04 +0100
Subject Iterate over text file, discarding some lines via context manager
From "fetchinson ." <fetchinson@googlemail.com>
Newsgroups comp.lang.python
Message-ID <mailman.16405.1417187079.18130.python-list@python.org> (permalink)

Show all headers | View raw


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
this:

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

    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 )

Cheers,
Daniel


-- 
Psss, psss, put it down! - http://www.cafepress.com/putitdown

Back to comp.lang.python | Previous | Next — Next in thread | Find similar | Unroll thread


Thread

Iterate over text file, discarding some lines via context manager "fetchinson ." <fetchinson@googlemail.com> - 2014-11-28 16:04 +0100
  Re: Iterate over text file, discarding some lines via context manager "ast" <nomail@invalid.com> - 2014-11-28 18:06 +0100
    Re: Iterate over text file, discarding some lines via context manager Dave Angel <davea@davea.name> - 2014-11-28 12:40 -0500
      Re: Iterate over text file, discarding some lines via context manager Marko Rauhamaa <marko@pacujo.net> - 2014-11-28 19:55 +0200
        Re: Iterate over text file, discarding some lines via context manager Chris Angelico <rosuav@gmail.com> - 2014-11-29 05:02 +1100
          Re: Iterate over text file, discarding some lines via context manager Marko Rauhamaa <marko@pacujo.net> - 2014-11-28 20:04 +0200

csiph-web