I'm trying to split a file with a list comprehension using code similar to:
lines = [x for x in re.split(r"\n+", file.read()) if not re.match(r"com", x)]
However, the lines list always has an empty string as the last element. Does anyone know a way to avoid this (excluding the cludge of putting a pop() afterwards)?
Best Solution
Put the regular expression hammer away :-)
readlines()
is almost obsolete these days.str.strip()
(and its friends,lstrip()
andrstrip()
).file
as a variable name. It's bad form, becausefile
is a built-in function.You can write your code as:
If you are still getting blank lines in there, you can add in a test:
If you really want it in one line:
Finally, if you're on python 2.6, look at the with statement to improve things a little more.