I have some code that reads a file of names and creates a list:
names_list = open("names", "r").read().splitlines()
Each name is separated by a newline, like so:
Allman
Atkinson
Behlendorf
I want to ignore any lines that contain only whitespace. I know I can do this by by creating a loop and checking each line I read and then adding it to a list if it’s not blank.
I was just wondering if there was a more Pythonic way of doing it?
I would stack generator expressions:
Now,
linesis all of the non-blank lines. This will save you from having to call strip on the line twice. If you want a list of lines, then you can just do:You can also do it in a one-liner (exluding
withstatement) but it’s no more efficient and harder to read:Update:
I agree that this is ugly because of the repetition of tokens. You could just write a generator if you prefer:
Then call it like:
update 2:
and on CPython (with deterministic reference counting)
In Python 2 use
itertools.ifilterif you want a generator and in Python 3, just pass the whole thing tolistif you want a list.