[Tutor] Testing for empty line
Danny Yoo
dyoo@hkn.eecs.berkeley.edu
Mon, 12 Nov 2001 15:00:44 -0800 (PST)
On Mon, 12 Nov 2001, Mike Yuen wrote:
> This is a simple question. How do I test for an empty line when i'm
> reading in a file?
If you're reading the file, line by line, using readline() or readlines(),
then an "empty" line will only contain the newline character "\n". You
can take advantage of this by using a comparison against this newline
string:
###
if line == '\n':
print "This is an empty line."
###
However, be careful about what an "empty" line looks like --- a line
containing spaces wouldn't be considered empty by this comparison, so you
might need to do something more, like strip()ping out whitespace. Here's
one possible definition that might help:
###
def isEmptyLine(line):
if string.strip(line) == '':
return 1
return 0
###
If you have more questions, please feel free to ask!