converting pipe delimited file to fixed width
MRAB
google at mrabarnett.plus.com
Thu Mar 19 12:16:27 EDT 2009
digz wrote:
> Hi,
> I am trying to convert a | delimited file to fixed width by right
> padding with spaces, Here is how I have written the program , just get
> the feeling this can be done in a much better ( python functional )
> way rather than the procedural code i have below . Any help
> appreciated
>
> #!/usr/bin/python
> def rightFill(fillString, toLength, fillChar):
> return fillString+''.join([fillChar for x in range(len
> (fillString),toLength)])
>
> fieldWidth=[ 14, 6, 18, 21, 21,4, 6 ];
>
> file = open("/home/chatdi/input.csv", "r");
> lines = file.readlines()
> file.close()
>
> out = open( "/home/chatdi/ouptut.csv", 'w')
> for line in lines:
> line = line[:-1]
> index = 0
> for token in line.split('|'):
> paddedToken = rightFill(token, fieldWidth[index], ' ' )
> out.write( paddedToken )
> index = index + 1
> out.write("\n")
>
Here's my version:
#!/usr/bin/python
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()
More information about the Python-list
mailing list