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

Jorgen Grahn grahn+nntp at snipabacken.se
Wed Nov 5 07:15:08 EST 2008


On Tue, 04 Nov 2008 15:36:23 -0600, Larry Bates <larry.bates at vitalEsafe.com> wrote:
> bearophileHUGS 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