Groups | Search | Server Info | Keyboard shortcuts | Login | Register [http] [https] [nntp] [nntps]
Groups > comp.lang.python > #81701
| Date | 2014-11-28 11:24 -0700 |
|---|---|
| From | Michael Torrie <torriem@gmail.com> |
| Subject | Re: Iterate over text file, discarding some lines via context manager |
| References | <CADjSo4Ro3xFj9T9gj0NO7YESE6G873vvrBD=Y=OAk-jNBRD5Bw@mail.gmail.com> |
| Newsgroups | comp.lang.python |
| Message-ID | <mailman.16416.1417199058.18130.python-list@python.org> (permalink) |
On 11/28/2014 08: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:
I'd personally do it with a generator function.
def filter(input):
for line in input:
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
yield items
for line_items in filter(open( 'myfile' )):
process( items )
For an excellent presentation on this sort of thing, see:
http://www.dabeaz.com/generators/
Back to comp.lang.python | Previous | Next | Find similar | Unroll thread
Re: Iterate over text file, discarding some lines via context manager Michael Torrie <torriem@gmail.com> - 2014-11-28 11:24 -0700
csiph-web