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


Groups > comp.lang.python > #81686 > unrolled thread

Re: Iterate over text file, discarding some lines via context manager

Started by"fetchinson ." <fetchinson@googlemail.com>
First post2014-11-28 16:44 +0100
Last post2014-11-28 16:44 +0100
Articles 1 — 1 participant

Back to article view | Back to comp.lang.python

This discussion starts older than the indexed window; earlier articles aren't shown. The article labeled Started by below is the oldest one visible, not the original post.


Contents

  Re: Iterate over text file, discarding some lines via context manager "fetchinson ." <fetchinson@googlemail.com> - 2014-11-28 16:44 +0100

#81686 — Re: Iterate over text file, discarding some lines via context manager

From"fetchinson ." <fetchinson@googlemail.com>
Date2014-11-28 16:44 +0100
SubjectRe: Iterate over text file, discarding some lines via context manager
Message-ID<mailman.16407.1417189445.18130.python-list@python.org>
On 11/28/14, Dave Angel <davea@davea.name> wrote:
> On 11/28/2014 10:04 AM, fetchinson . wrote:
>> 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 )
>>
>
> I see what you're getting at, but a context manager is the wrong
> paradigm.  What you want is a generator.   (untested)
>
> def mygenerator(filename):
>      with open(filename) as f:
>          for line in f:
>              if not line: continue
>              if line.startswith('#'): continue
>              items = line.split()
>              if not items: continue
>              yield items
>
> Now your caller simply does:
>
> for items in mygenerator(filename):
>        process(items)

Great, thanks a lot!

Cheers,
Daniel


>
> --
> DaveA
> --
> https://mail.python.org/mailman/listinfo/python-list
>


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

[toc] | [standalone]


Back to top | Article view | comp.lang.python


csiph-web