converting pipe delimited file to fixed width

odeits odeits at gmail.com
Thu Mar 19 12:52:00 EDT 2009


On Mar 19, 8:51 am, digz <Digvijo... at gmail.com> 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")


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.

I use the csv module to do the reading of the file, i am going to do
some testing to see if i can set the delimiter to '' so that i can
also use it for the output. For now this should work.


http://docs.python.org/library/csv.html


import csv

fieldWidth=[ 14, 6, 18, 21, 21,4, 6  ];
csvfilepath = 'somefile.csv'

outcsvfilepath = 'someoutfile.csv'
endl = '\n'

f = open(csvfilepath)
outf = open(outcsvfilepath)


csvfile = csv.reader(f,delimiter = '|')

for row in csvfile:
	outrow = [ field + fillchar * (width - len(field)) for width, field
in zip(fieldWidth,row)]
	outcsv.write( ''.join(outrow))
	outcsv.write( endl )

f.close()
outf.close()




More information about the Python-list mailing list