Reputation: 2446
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 python by the way.
Upvotes: 1
Views: 5701
Reputation: 26586
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']
>>>
Upvotes: 2
Reputation: 798626
for line in someopenfile:
if line.isspace():
empty_line()
Upvotes: 10