Skip to content
Advertisement

python: how to check if a line is an empty line

Trying to figure out how to write an if cycle to check if a line is empty.

The file has many strings, and one of these is a blank line to separate from the other statements (not a ""; is a carriage return followed by another carriage return I think)

new statement
asdasdasd
asdasdasdasd

new statement
asdasdasdasd
asdasdasdasd

Since I am using the file input module, is there a way to check if a line is empty?

Using this code it seems to work, thanks everyone!

for line in x:

    if line == 'n':
        print "found an end of line"

x.close()

Advertisement

Answer

If you want to ignore lines with only whitespace:

if line.strip():
    ... do something

The empty string is a False value.

Or if you really want only empty lines:

if line in ['n', 'rn']:
    ... do  something
Advertisement