What is the correct format to write float value to file in Python

What is the correct format to write float value to file in Python

The write function takes a single string. Youre trying to use it like print, which takes any number of arguments.


You can, in fact, just use print. Its output only goes to your programs output (stdout) by default, by passing it a file argument, you can send it to a text file instead:

print(This is x1: , x1, file=f)

If you want to use write, you need to format your output into a single string. The easiest way to do that is to use f-strings:

f.write(fThis is x1: {x1}n)

Notice that I had to include a n on the end. The print function adds its end parameter to the end of what it prints, which defaults to n. The write method does not.


Both for backward compatibility and because occasionally theyre more convenient, Python has other ways of doing the same thing, including explicit string formatting:

f.write(This is x1: {}n.format(x1))

printf-style formatting:

f.write(This is x1: %sn % (x1,))

template strings:

f.write(string.Template(This is $x1n).substitute(x1=x1))

… and string concatenation:

f.write(This is x1:  + str(x1) + n)

All but the last of these automatically converts x1 to a string in the same way as str(x1), but also allows other options, like:

f.write(fThis is {x1:.8f}n)

This converts x1 to a float, then formats it with 8-decimal precision. So, in addition to printing out 1.11111111 and 2.22222222 with 8 decimals, itll also print 1.1 as 1.10000000 and 1.23456789012345 as 1.23456789.

The same format strings work for f-strings, str.format, and the format functions:

print(This is x1: , format(x1, .8f), file=f)
f.write(This is x1: {:.8f}n.format(x1))
f.write(This is x1:  + format(x1, .8f) + n)

… and the other two methods have similar, but not quite as powerful, formatting languages of their own:

f.write(This is x1: %.8fn % (x1,))

the way you are writing to the file looks like you are giving two arguments to write function. So you need to only pass one argument. try converting x1 and x2 into string and then write to the file.

f.write(This is x1  + str(x1))
f.write(This is x2  + str(x2))

What is the correct format to write float value to file in Python

f.write(This is x1: %f%x1)
f.write(This is x2: %f%x2) 

Leave a Reply

Your email address will not be published. Required fields are marked *