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

Larry Bates larry.bates at vitalEsafe.com
Tue Nov 4 22:36:23 CET 2008


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)
> 
> xlines = (line for line in open(filename) if line.strip())
> 
> Bye,
> bearophile

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:

fp = open(filename, 'r')
for line in fp:
     if not line.strip():
         continue

     #
     # Do something with the non-blank like:
     #


fp.close()

-Larry



More information about the Python-list mailing list