[python-win32] Get Blank Lines in a text file

John Machin sjmachin at lexicon.net
Fri Jul 4 12:59:18 CEST 2008


siddhartha veedaluru wrote:
> Hi,

Your problem is nothing to do with Windows at all; a better target would 
have been the comp.lang.python newsgroup or the python-list at python.org 
mailing list [but NOT both; messages are gatewayed both ways].

>  
> As part of a task i need to verify that last line of a text file is blank.
> When i read that file, its getting ignored and i couldn't able to check 
> that.
> Here is the code snippet that i used:
>  
> import os

You don't use "os" ...

> iniFileName = "Config.ini"
> iniFile = open(iniFileName, 'r')
> lines = iniFile.readlines()
> noOfLines = len(lines)
> if lines[noOfLines] == "":

You say "its getting ignored"; I say it should raise an IndexError 
exception (see below). When asking about a problem, always show the 
exact code that you ran, and any output (including any traceback and 
error message).

 >>> lines = ['a\n', 'b\n', '\n']
 >>> n = len(lines)
 >>> lines[n]
Traceback (most recent call last):
   File "<stdin>", line 1, in <module>
IndexError: list index out of range
 >>> n
3
 >>> lines[2]
'\n'
 >>> lines[-1]
'\n'
 >>>

You can access the last line as lines[-1] (see above).

Now we need to think about what you mean by "blank". The last line in a 
file will usually end with '\n' but may not. That's problem 1. Problem 2 
is that it may contain spaces, tabs, and/or (rarely) other forms of 
whitespace. So testing against only "" is not a good idea. You can cover 
all those bases by using the strip method.

Oh and you'd better test that you do have a last line. Putting it all 
together:
DEBUG = True
if not lines:
     print "No lines"
else:
     if DEBUG:
         # If you can't understand what's happening in your program,
         # do some debugging!
         print "Last line is", repr(lines[-1])
     if lines[-1].strip():
         print "Last line is NOT blank" # Note: I changed the order
     else:
         print "Last line is blank"

Hope this helps,
John


More information about the python-win32 mailing list