converting pipe delimited file to fixed width

MRAB google at mrabarnett.plus.com
Thu Mar 19 19:21:53 CET 2009


John Posner wrote:
> [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()
> 
Alternatively:

#!/usr/bin/python

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

# build the format for the output line
fmt = "".join("%%-%ds" % width for width in field_widths) + "\n"

out = open("/home/chatdi/ouptut.csv", 'w')
for line in open("/home/chatdi/input.csv", "r"):
     out.write(fmt % tuple(line.rstrip().split('|')))

out.close()



More information about the Python-list mailing list