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

Python

Python Problem Overview


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()

Python Solutions


Solution 1 - Python

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', '\r\n']:
    ... do  something

Solution 2 - Python

I use the following code to test the empty line with or without white spaces.

if len(line.strip()) == 0 :
    # do something with empty line

Solution 3 - Python

line.strip() == ''

Or, if you don't want to "eat up" lines consisting of spaces:

line in ('\n', '\r\n')

Solution 4 - Python

You should open text files using rU so newlines are properly transformed, see http://docs.python.org/library/functions.html#open. This way there's no need to check for \r\n.

Solution 5 - Python

I think is more robust to use regular expressions:

import re

for i, line in enumerate(content):
    print line if not (re.match('\r?\n', line)) else pass

This would match in Windows/unix. In addition if you are not sure about lines containing only space char you could use '\s*\r?\n' as expression

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
Questionuser1006198View Question on Stackoverflow
Solution 1 - PythonretracileView Answer on Stackoverflow
Solution 2 - PythonbevardgisuserView Answer on Stackoverflow
Solution 3 - PythonFred FooView Answer on Stackoverflow
Solution 4 - PythonhochlView Answer on Stackoverflow
Solution 5 - PythonalemolView Answer on Stackoverflow