How to detect lines with only a white space in a text?
Given that "empty line" is a white space:
I am trying to read a text file line by line. I want to ignore whitespace lines. Or in a more correct way, I want to detect empty lines.
An empty line can contain spaces, newline characters, etc. And it is still considered as an empty line. If you open it up in notepad, in an empty line you should not see anything.
Is there a quick way of doing this in Python? I am new to pytho开发者_StackOverflow社区n by the way.
for line in someopenfile:
if line.isspace():
empty_line()
Using strip()
on any string returns a string with all leading and trailing whitespace stripped. So calling that on a line with only whitespace gives you an empty string. You can then just filter on strings with non-zero length.
>>> lines=[' ','abc','']
>>> print filter(lambda x:len(x.strip()),lines)
['abc']
>>>
精彩评论