Search code examples
pythonfilefor-loopleftalign

How to write to .txt file with left align text in python?


I'm trying to write data to a txt file in a for loop using the code [python]:

f = open('top_5_predicted_class.txt', 'w')
    f.write('Predicted Classes' + '\t\t' + ' Class Index' + '\t' + ' Probability' + '\n\n')

    for i in range(0, 5):
        f.write("%s \t \t %s \t \t %s \n" % (labels[top_k][i], top_k[i], out['prob'][0][top_k][i]) )
    f.close()

But the output that I got was not what I was expecting. I want to have class index all left aligned as well as the probabilities.

output

Any idea of how can I do this? I guess the problem exists because the length of the predicted classes is not fixed.


Solution

  • You shouldn't use tabs for this kind of alignment, since the behavior is unpredictable when your inputs are of different length. If you know what the maximum length of each column is, you can use the format function to pad with spaces. In my example, I use 15 spaces:

    >>> for a,b,c in [('a','b','c'), ('d','e','f')]:
    ...     print ("{: <15} {: <15} {: <15}".format(a, b, c))
    ...
    a               b               c
    d               e               f
    

    This is purely about display though. If you are concerned about storing the data, it would be much better to use CSV format, such as with Python's csv module.