Working with fixed format text db's
frank at chagford.com
Sat Jun 9 10:04:20 CEST 2007
On Jun 8, 5:50 pm, Neil Cerutti <horp... at yahoo.com> wrote:
> 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
> new = file("new.dat", "w")
> if not new:
> print "Error. Could not open file new.dat for writing."
> raw_input("Press Return To Exit.")
> for s in freshmen:
> new.write(' '.ljust(10)) # Phone Number
> new.write(' '.ljust(1254)) # Empty 'filler' space.
> new.write('2813 ')
I have to do this occasionally, and also find it cumbersome.
I toyed with the idea of posting a feature request for a new 'fixed
length' string formatting operator, with optional parameters for left/
right-justified and space/zero-filled.
We already have '%-12s' to space fill for a length of 12, but it is
not truly fixed-length, as if the value has a length greater than 12
you need it to be truncated, and this construction will not do that.
Assume we have a new flag '!n', which defaults to left-justified and
space-filled, but allows an optional 'r' and '0' to override the
Then the above example could be written as
format = '%!9s%!10s%!16s%!11s%!10s%!1254s%!6s%!5s'
for s in freshmen:
new.write (format %
' ',' ','2813',s.major))
I never felt strongly enough about it to propose it, but I thought I
would mention it.
More information about the Python-list