Groups | Search | Server Info | Keyboard shortcuts | Login | Register [http] [https] [nntp] [nntps]
Groups > comp.lang.python > #81701 > unrolled thread
| Started by | Michael Torrie <torriem@gmail.com> |
|---|---|
| First post | 2014-11-28 11:24 -0700 |
| Last post | 2014-11-28 11:24 -0700 |
| 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.
Re: Iterate over text file, discarding some lines via context manager Michael Torrie <torriem@gmail.com> - 2014-11-28 11:24 -0700
| From | Michael Torrie <torriem@gmail.com> |
|---|---|
| Date | 2014-11-28 11:24 -0700 |
| Subject | Re: Iterate over text file, discarding some lines via context manager |
| Message-ID | <mailman.16416.1417199058.18130.python-list@python.org> |
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 top | Article view | comp.lang.python
csiph-web