converting pipe delimited file to fixed width

John Posner jjposner at snet.net
Thu Mar 19 18:55:27 CET 2009


[snip]
 
> field_widths = [14, 6, 18, 21, 21, 4, 6]
> 
> out = open("/home/chatdi/ouptut.csv", 'w')
> for line in open("/home/chatdi/input.csv", "r"):
>     fields = line.rstrip().split('|')
>     padded_fields = [field.ljust(width) for field, width in zip(fields, field_widths)]
>     out.write("".join(padded_fields) + "\n")
> 
> out.close()

How about a version that uses Python 3.0 string formatting:

  field_widths = [14, 6, 18, 21, 21, 4, 6]

  out = open(r"c:\temp\output.csv", 'w')
  for line in open(r"c:\temp\input.csv", "r"):
      fields = line.rstrip().split('|')
      outline = ""
      for pair in zip(fields, field_widths):
          outline += "{0:{1}}".format(*pair)
      out.write(outline + "\n")
  out.close()

Or, if you hate NLs (and, perhaps, like obfuscation):

  field_widths = [14, 6, 18, 21, 21, 4, 6]

  out = open(r"c:\temp\output.csv", 'w')
  for line in open(r"c:\temp\input.csv", "r"):
      fields = line.rstrip().split('|')
      out.write("".join(["{0:{1}}".format(*pair) for pair in \
                zip(fields, field_widths)]) + "\n")
  out.close()




More information about the Python-list mailing list