简体   繁体   中英

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.

产量

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

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.

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]))

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM