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

Ben Finney bignose+hates-spam at benfinney.id.au
Wed Nov 5 00:25:06 CET 2008


tmallen <thomasmallen at gmail.com> writes:

> On Nov 4, 4:30 pm, bearophileH... at lycos.com wrote:
> > xlines = (line for line in open(filename) if line.strip())
> 
> I must be missing something:
> 
> >>> xlines = (line for line in open("new.data") if line.strip())
> >>> xlines
> <generator object at 0x6b648>

A generator <URL:http://www.python.org/dev/peps/pep-0255> is a
sequence, but is not a collection. It will generate each item on
request, rather than having them all in memory at once.

    for line in xlines:
        do something_knowing_the_line_is_not_blank(line)

If you later *want* a collection containing all the items from the
generator, you can feed the generator (or any iterable) to a type that
can turn it into a collection. For example, to get all the filtered
lines as a list:

    all_lines = list(xlines)

Note that some generators (not this one, which will end because the
file is finite size) never end, so feeding them to a constructor this
way will never return.

-- 
 \     “It is far better to grasp the universe as it really is than to |
  `\    persist in delusion, however satisfying and reassuring.” —Carl |
_o__)                                                            Sagan |
Ben Finney



More information about the Python-list mailing list