I need to write several floats to file for which I am using the format()
method. What I want is to round the floats to a given number of decimal places and write them aligned at the same time.
Here's a MWE:
a = 546.35642
b = 6785.35416
c = 12.5235
d = 13.643241
line = [str('{:.2f}'.format(a)),
str('{:.4f}'.format(b)),
str('{:.5f}'.format(c)),
str('{:.3f}'.format(d))]
with open('format_test.dat', "a") as f_out:
f_out.write('''{:>10} {:>15} {:>16} {:>15}'''.format(*line))
f_out.write('\n')
This gets the job done but it seems awfully convoluted to me. Is there a better way to do this using format()
?
You can just add the .#f
in the format with the alignment.
with open('format_test.dat', "a") as f_out:
f_out.write('''{:>10.2f} {:>15.4f} {:>16.5f} {:>15.3f}'''.format(a, b, c, d))
f_out.write('\n')
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With