0

I have my below that takes entire values and outputs them into another file.

with open('candidatevalues2.txt', 'w') as outfile:
    outfile.write('plate mjd fiberid FWHM erFWHM loglum loglumerr logBHmass logBhmasserr  ksvalue pvalue\n')
for i in range(9):
    with open('candidatevalues2.txt', 'a') as outfile:
        dmpval= stats.ks_2samp(y_real[i], yfit[i])
        outfile.write('{0} {1} {2} {3} {4} {5} {6} {7} {8} {9} {10}\n'.format(plate[i], mjd[i], fiberid[i], fwhm[i], fwhmer[i], loglum[i], loglumerr[i], logbhmass[i], logbhmasserr[i], dmpval[0], dmpval[1]))

The first few lines of the file show as:

plate mjd fiberid FWHM erFWHM loglum loglumerr logBHmass logBhmasserr ksvalue pvalue

590 52057 465 1710.58526651 115.154250367 42.0681732777 0.070137615974 6.81880343617 0.15451686304 0.0909090909091 0.970239478143

1793 53883 490 1736.15809558 144.074772803 40.160433977 0.0736271164581 5.7828225787 0.13016470738 0.0909090909091 0.970239478143

648 52559 335 1530.9128304 153.965617385 40.8584948115 0.110687643929 6.05420009544 0.155678567881 0.0909090909091 0.970239478143

I am wondering how do I reduce all the values to just 2 decimal places?

jonrsharpe
  • 115,751
  • 26
  • 228
  • 437
user1821176
  • 1,141
  • 2
  • 18
  • 29

1 Answers1

1

I know, it takes a while to learn using .format in python, the spec for format is a bit hidden.

Short lesson on using python string format method

Here are few iterations how could be the code modified:

Original code:

 outfile.write('{0} {1} {2} {3} {4} {5} {6} {7} {8} {9} {10}\n'.format(plate[i], mjd[i], fiberid[i], fwhm[i], fwhmer[i], loglum[i], loglumerr[i], logbhmass[i], logbhmasserr[i], dmpval[0], dmpval[1]))

Simplify to make explanation easier and shorter:

 outfile.write('{0} {1} {2}\n'.format(plate[i], dmpval[0], dmpval[1]))

Separate formatting template and rendering:

 templ = '{0} {1} {2}\n'
 outfile.write(templ.format(plate[i], dmpval[0], dmpval[1]))

Specify 2 decimal places format:

 templ = '{0:.2f} {1:.2f} {2:.2f}\n'
 outfile.write(templ.format(plate[i], dmpval[0], dmpval[1]))

Now you shall have, what you have asked for.

Using templ.format(**locals()) idiom

In case, you want to render content of variables directly available by name, by name and property (using dot notation) or by name and constant positive index, you may use them directly in template and use a trick, that locals() returns dictionary of locally available variable and **locals() makes them available as keyword variable in the call:

 plate_i = plate[i]
 templ = '{plate_i:.2f} {dmpval[0]:.2f} {dmpval[1]:.2f}\n'
 outfile.write(templ.format(**locals()))

However, you see, that this will not work for index being specified by another variable, that is why I had to introduce new variable plate_i.

Jan Vlcinsky
  • 42,725
  • 12
  • 101
  • 98