Add Number to First Number on Each Line of File then Write to Another File - Python Python program adds a value to the first number in a fixed width file of variable length. Normally one line header. Before user deletes original file and renames new file they need to check it.

How can the error handling be improved?

# Add number to first number on each line of file then write to another file
#
# Initialise
infile = 'egtxt.prn'
hdrln = 1
llen = 0
fw = 7  # Field width of first number on line
add = 80.0  # Add value to first number on line

print ('Processing {}, first number is {} characters wide, adding {} ...'.format(infile, fw, add))

ifile = open(infile, 'r')
tfile = open(infile+'.out', 'w')
# Skip header
line = ifile.readline()
tfile.write (line)

while True:
    line = ifile.readline()
    if not line:
        break
    llen = len(line) - fw
    tfile.write ('{:{sfw}.{sprec}f}{}'.format(float(line[:fw])+add, line[-llen:], sfw=str(fw), sprec='2'))

# Finalise
ifile.close()
tfile.close()
print (' done.')


Sample egtxt.prn follows:

ID      Name               Address                         Comment
   2.88 Barnett, Irene A.  P.O. Box 829, 4484 Aliquet Ave  viverra. Maecenas iaculis
  30.58 Irwin, Honorato X. Ap #446-1219 Nisi. Road         dui
3428.21 Talley, Bree S.    862-3586 Duis Ave               leo. Morbi
 176.12 Hensley, Kai T.    Ap #842-3806 Class Street       eu
Constants uppercase

A very widespread convention is that constants should be uppercase, so please conform to the standard for readability.

Unused variables

hdrln = 1
llen = 0


The first one is never used, the second one is never used with the original value, so I suggest removing that declaration.

with and iterable interface for files

with is a commonly used to keyword to simplify working with files to take care of automatic closing, also files are iterable so you can just do: for line in file that should simplify your code.

Isolate logic in functions

tfile.write ('{:{sfw}.{sprec}f}{}'.format(float(line[:fw])+add, line[-llen:], sfw=str(fw), sprec='2'))


That should be in its function along with documentation because it is the main part of the program, the logic should be highlighted and explained not hidden inside the boilerplate.