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

bearophileHUGS at lycos.com bearophileHUGS at lycos.com
Tue Nov 4 18:33:02 EST 2008


tmallen
> I must be missing something:
>
> >>> xlines = (line for line in open("new.data") if line.strip())
> >>> xlines
> <generator object at 0x6b648>
> >>> xlines.sort()
> Traceback (most recent call last):
>   File "<stdin>", line 1, in <module>
> AttributeError: 'generator' object has no attribute 'sort'
>
> What do you think?

Congratulations, you have just met your first lazy construct ^_^
That's a generator, it yields nonblank lines one after the other. This
can be really useful.
If you want a real array of items, then you can do this:
lines = list(xlines)
Or use a list comp.:
lines = [line for line in open("new.data") if line.strip()]

Bye,
bearophile



More information about the Python-list mailing list