Is there a better/simpler way to filter blank lines?
clp at rebertia.com
Tue Nov 4 23:52:17 CET 2008
On Tue, Nov 4, 2008 at 2:30 PM, tmallen <thomasmallen at gmail.com> wrote:
> On Nov 4, 4:30 pm, bearophileH... at lycos.com wrote:
>> > 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())
> I must be missing something:
>>>> xlines = (line for line in open("new.data") if line.strip())
> <generator object at 0x6b648>
> Traceback (most recent call last):
> File "<stdin>", line 1, in <module>
> AttributeError: 'generator' object has no attribute 'sort'
> What do you think?
xlines is a generator, not a list. If you don't know what a generator
is, see the relevant parts of the Python tutorial/manual (Google is
To sort the generator, you can use 'sorted(xlines)'
If you need it to actually be a list, you can do 'list(xlines)'
Follow the path of the Iguana...
More information about the Python-list