On Jun 8, 5:50 pm, Neil Cerutti <[EMAIL PROTECTED]> 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 > 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)) >
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 defaults. Then the above example could be written as format = '%!9s%!10s%!16s%!11s%!10s%!1254s%!6s%!5s' for s in freshmen: new.write (format % (s.ssn,s.id,s.last,s.first, ' ',' ','2813',s.major)) I never felt strongly enough about it to propose it, but I thought I would mention it. Frank Millman -- http://mail.python.org/mailman/listinfo/python-list