Not able to read blank lines and spaces on a small text file

Peter Hansen peter at engcorp.com
Mon Sep 13 11:08:04 EDT 2004


Ruben wrote:

> while record != "":
>         try:
>                 record = input_file.readline()
>                 key_value_pair = record.split()
>                 key = key_value_pair[0]
>                 value = key_value_pair[1:]
>                 concatenated_value= ' '.join(value)
>                 if record == "": 
> 			empty_string_lines += 1
> 			print " Victor Empty string lines = ", empty_string_lines
> 			break                
>         except IndexError:
>                 break

The first time this code reads a line which doesn't
contain whitespace separated records, the record.split()
call will return an empty list, and the next line will
try to retrieve the first element from it, raising an
IndexError, which will terminate the loop.

Your code doesn't seem to be following any of the usual
Python idioms.  I suggest starting with the following pattern
instead, and growing the code from there:

input_file = open(...)
try:
     for record in input_file:
         if record.strip() == '':  # blank line, ignore
             continue

         # record-processing code follows here
         key_value_pair = record.split()
         key = key_value_pair[0]
         ... etc....

finally:
     input_file.close()


The above pattern will allow the record-processing code
to handle *only* non-blank lines (including lines that
have just empty whitespace), simplify everything immensely.

-Peter



More information about the Python-list mailing list