Search code examples
pythontextfile-iostring-formattingrewriting

writing to a text file with proper allign


What is the best to write to a text file I was trying

>>> a = ['short', 'longline', 'verylongline']
>>> b = [123, 2347575, 8]
>>> ww = open("write_proper.txt", "w")
>>> for each in xrange(3):
...    ww.write("%s\t%s\n" % (a[each], b[each]))
...
>>> ww.close()

which produced output:

short   123
longline    2347575
verylongline    8

Is there any way where contents can be properly spaced to look pretty:

short           123
longline        2347575
verylongline    8

So that it considers the longest length of contents in the 1st column and places the 2nd column acccordingly!


Solution

  • If you know the field width a priori, then you can include the field width in your format specification:

    ww.write("%-12s\t%s\n" % (a[each], b[each]))
    

    If you want it to be data sensitive, try:

    awidth = max(len(x) for x in a)
    ...
    ww.write("%-*s\t%s\n" % (awidth, a[each], b[each]))
    

    Reference: https://docs.python.org/2/library/stdtypes.html#string-formatting-operations