Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

I have a bunch of float values, for example:

x1 = 1.11111111

x2 = 2.22222222

I want to write these values to a file:

f = open("a.dat", "w+")
f.write("This is x1: ",x1)
f.write("\n")              #I want to separate the 2 lines
f.write("This is x2: ",x2)

At this point I got an error on the second line:

write() takes exactly one argument (2 given)

How do I write to file such that when I open it, I see this format:

This is x1: 1,1111111
This is x2: 2,2222222

And yes, the file has to be ***.dat

It's not .txt

like image 578
Tamamo Avatar asked Oct 18 '25 17:10

Tamamo


1 Answers

The write function takes a single string. You're 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 program's 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(f"This 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 they're 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: %s\n" % (x1,))

… template strings:

f.write(string.Template("This is $x1\n").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(f"This 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, it'll 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: %.8f\n" % (x1,))
like image 120
abarnert Avatar answered Oct 21 '25 06:10

abarnert