Caveat: none of the solutions (including mine) deal with the case of
the field being longer than the width. You might want to throw an
exception.

Alternatively, you can just crop the results. Tweaking MRAB's elegant solution:

  field_widths = [14, 6, 18, 21, 21, 4, 6]
  infile = open("input.csv")
  out = open("ouptut.csv", 'w')

  for fields in csv.reader(infile, delimiter='|'):
     padded_fields = [
       # pad, and then crop
       field.ljust(width)[:width]
       for field, width
       in zip(fields, field_widths)
       ]
     out.write("".join(padded_fields) + "\n")

  infile.close()
  out.close()

If you want them right-justified, you can use

  field.rjust(width)[-width:]

-tkc



--
http://mail.python.org/mailman/listinfo/python-list

Reply via email to