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

Steve Holden steve at holdenweb.com
Tue Nov 4 20:25:09 EST 2008


tmallen wrote:
> On Nov 4, 4:30 pm, 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)
>> xlines = (line for line in open(filename) if line.strip())
>>
>> Bye,
>> bearophile
> 
> 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?
> 
I think there'd be no advantage to a sort method on a generator, since
theoretically the last item could be the first required in the sorted
sequence, so it's necessary to hold all items in memory to ensure the
sort is correct. So there's no point using a generator in the first place.

regards
 Steve
-- 
Steve Holden        +1 571 484 6266   +1 800 494 3119
Holden Web LLC              http://www.holdenweb.com/




More information about the Python-list mailing list