Search code examples
pythonpandasnumpyfixed-width

padding spaces at right while writing data frame to fwf


I am writing Pandas Data Frame to a fixed width file using numpy. Here is my code.

with open(self.tablePath,mode) as ofile:
   np.savetxt(ofile, tdata.values, fmt='%4s%12s%15s')

This code adds the spaces to the left side of every column values. How do I padding the spaces at the right side of the every column values? I get the result as following,

xxxx        yyyy         256.25
xxx1      yyyyy1         430.25

But I want my result as follows,

xxxxyyyy        256.25         
xxx1yyyyy1      430.25         

Solution

  • As an old C programmer I remember that minus (-) means right padding. You just need:

    with open(self.tablePath,mode) as ofile:
       np.savetxt(ofile, tdata.values, fmt='%-4s%-12s%-15s')