Working with fixed format text db's

Neil Cerutti horpner at yahoo.com
Fri Jun 8 17:50:26 CEST 2007


Many of the file formats I have to work with are so-called
fixed-format records, where every line in the file is a record,
and every field in a record takes up a specific amount of space.

For example, one of my older Python programs contains the
following to create a fixed-format text record for a batch of new
students:

new = file("new.dat", "w")
if not new:
    print "Error. Could not open file new.dat for writing."
    raw_input("Press Return To Exit.")
    sys.exit(1)

for s in freshmen:
    new.write(s.ssn.ljust(9))
    new.write(s.id.ljust(10))
    new.write(s.last[:16].ljust(16))
    new.write(s.first[:11].ljust(11))
    new.write(' '.ljust(10)) # Phone Number
    new.write(' '.ljust(1254)) # Empty 'filler' space.
    new.write('2813  ')
    new.write(s.major.ljust(5))
    
    # Etc...

Luckily, the output format has not changed yet, so issues with
maintaining the above haven't arisen.

However, I'd like something better.

Is there already a good module for working with fixed format
records available? I couldn't find one.

If not, please suggest how I might improve the above code.

-- 
Neil Cerutti
When "yearn" was sung, the performers ounded like they were in a state of
yearning. --Music Lit Essay



More information about the Python-list mailing list