Writing to a file with formatting using write()

If you want to control the formatting, there is another way. The example below illustrates how to write the float x and its square x*x to a file called output. In this example we write the values in fixed-point notation with two digits after the decimal point.

fp =  open("output","w")
fp.write("{0:5.2f} {1:5.2f}\n".format(x,x*x))
fp.close()

The write() method takes only a string, so we need to convert the floats to strings. There are various ways to do that. Here we have used the formatting procedure. Notice that to end the line, we need to include an explicit new-line character "\n".

The write() method returns the number of characters written. So if you are running in interactive mode, you will see that value printed on your screen. If you put the command in a script, you can capture it if you want using

chars = fp.write("{0:5.2f} {1:5.2f}\n".format(x,x*x))

but ignoring it is also OK.