converting pipe delimited file to fixed width
Tim Chase
python.list at tim.thechases.com
Thu Mar 19 13:40:14 EDT 2009
> 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
More information about the Python-list
mailing list