Is there a better/simpler way to filter blank lines?

tmallen thomasmallen at gmail.com
Wed Nov 5 21:55:26 CET 2008


Why do I feel like the coding style in Lutz' "Programming Python" is
very far from idiomatic Python? The content feels dated, and I find
that most answers that I get for Python questions use a different
style from the sort of code I see in this book.

Thomas

On Nov 5, 7:15 am, Jorgen Grahn <grahn+n... at snipabacken.se> wrote:
> On Tue, 04 Nov 2008 15:36:23 -0600, Larry Bates <larry.ba... at vitalEsafe.com> wrote:
> > bearophileH... at lycos.com wrote:
> >> tmallen:
> >>> I'm parsing some text files, and I want to strip blank lines in the
> >>> process. Is there a simpler way to do this than what I have here?
> >>> lines = filter(lambda line: len(line.strip()) > 0, lines)
>
> ...
>
> > Of if you want to filter/loop at the same time, or if you don't want all the
> > lines in memory at the same time:
>
> Or if you want to support potentially infinite input streams, such as
> a pipe or socket.  There are many reasons this is my preferred way of
> going through a text file.
>
> > fp = open(filename, 'r')
> > for line in fp:
> >      if not line.strip():
> >          continue
>
> >      #
> >      # Do something with the non-blank like:
> >      #
>
> > fp.close()
>
> Often, you want to at least rstrip() all lines anyway,
> for other reasons, and then the extra cost is even less:
>
>        line = line.rstrip()
>        if not line: continue
>        # do something with the rstripped, nonblank lines
>
> /Jorgen
>
> --
>   // Jorgen Grahn <grahn@        Ph'nglui mglw'nafh Cthulhu
> \X/     snipabacken.se>          R'lyeh wgah'nagl fhtagn!




More information about the Python-list mailing list