delete_this_account
delete_this_account

Reputation: 2446

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 python by the way.

Upvotes: 1

Views: 5701

Answers (2)

MAK
MAK

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

Ignacio Vazquez-Abrams
Ignacio Vazquez-Abrams

Reputation: 798626

for line in someopenfile:
  if line.isspace():
    empty_line()

Upvotes: 10

Related Questions