[Tutor] Can't detect empty line

dman dsh8290@rit.edu
Sun, 18 Nov 2001 14:34:46 -0500


On Sun, Nov 18, 2001 at 11:49:29AM -0700, Mike Yuen wrote:
| I know that I can detect an empty line when reading in a file simply by
| going:
| if line == '\n':
| 	# Do stuff
| 
| However, i'm having a serious problem trying to detect an empty line.
| I'm using Linux and when I do a "cat -ve input".  The line i'm interested
| in has a ^M$ implying there's a return character on that empty line.
| For some reason, it's reading in the line as if there's stuff on that
| empty line.
| 
| I've tried to strip, lstrip, etc to clean the line up so I might be able
| to better detect an empty line but no luck.

This is because *strip() removes all whitespace, including the
newline.

| Is there any other way to find detect an empty line?

You can use


while 1 :
    line = f.readline()
    if not line : break # EOF
    if line.strip() == "" :
        print "line was empty"
    else :
        print "line wasn't empty"


or you could use 


while 1 :
    line = f.readline()
    if not line : break # EOF
    if line.replace( '\r' , '' ) == "\n" :
        print "line was empty"
    else :
        print "line wasn't empty"



HTH,
-D