Filipa Almeida Filipa Almeida - 1 month ago 12
Python Question

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.

Answer

You can go through your data and get the maximum field widths and then use them to align everything:

data = [
    ['tabby, tabby cat', 281, 0.312437],
    ['tiger cat', 282, 0.237971],
    ['Egyption cat', 285, 0.123873],
    ['red fox, Vulpes vulpes', 277, 0.100757],
    ['lynx, catamount', 287, 0.709574]
]

max_class_width = len('Predicted Classes')
max_index_width = len('Class Index')
max_proba_width = len('Probability')

for entry in data:
    max_class_width = max(max_class_width, len(entry[0]))
    max_index_width = max(max_index_width, len(str(entry[1])))
    max_proba_width = max(max_proba_width, len(str(entry[2])))

print "{1:<{0}s}  {3:<{2}s}  {5:<{4}}".format(max_class_width, 'Predicted Classes',
                                              max_index_width, 'Class Index',
                                              max_proba_width, 'Probability')

for entry in data:
    print "{1:<{0}s}  {3:<{2}s}  {5:<{4}}".format(max_class_width, entry[0],
                                                  max_index_width, str(entry[1]),
                                                  max_proba_width, str(entry[2]))

Output

Predicted Classes       Class Index  Probability
tabby, tabby cat        281          0.312437   
tiger cat               282          0.237971   
Egyption cat            285          0.123873   
red fox, Vulpes vulpes  277          0.100757   
lynx, catamount         287          0.709574   

You can use also use printf style formatting:

print "%-*s  %-*s  %-*s" % (max_class_width, 'Predicted Classes',
                            max_index_width, 'Class Index',
                            max_proba_width, 'Probability')

for entry in data:
    print "%-*s  %-*s  %-*s" % (max_class_width, entry[0],
                                max_index_width, str(entry[1]),
                                max_proba_width, str(entry[2]))