To write a float to a file, you just have to open a file in write mode, convert the float to a string with str(), and use the write() function.
fl = 1.01
with open("example.txt", "w") as f:
f.write(str(fl))
If you want to add a float to an existing file and append to the file, then you need to open the file in append mode.
fl = 1.01
with open("example.txt", "a") as f:
f.write(str(fl))
When working with files in Python, the ability to create new files or modify existing files easily is important.
One such case is if you want to write a float to a file.
To write a float to a file, it is easy – you just have to open a file in write mode, convert the float to a string with str(), and use the write() function.
This is the same as if you wanted to write an int to a file.
Below is a simple example of how you can write a float to a file using Python.
fl = 1
with open("example.txt", "w") as f:
f.write(str(fl))
Append Variable to File Using Python
If you want to append a float to a file, then you should open the file in append mode.
Below is an example showing you how to append a float to a file in Python.
fl = 1.01
with open("example.txt", "a") as f:
f.write(str(fl))
How to Write Multiple Float Values to a File Using Python
If you want to write multiple float varaibles to a file using Python, you can build a string and then pass it to write().
For example, if you had multiple floats and wanted to print each one on it’s own line, then you could do the following in Python.
float1 = 1.01
float2 = 2.02
float3 = 3.03
with open("example.txt", "w") as f:
f.write(str(float1) + "n")
f.write(str(float2) + "n")
f.write(str(float3) + "n")
If you wanted to create a file where the floats were comma delimited, then you could print them all on one line and join them with a comma.
float1 = 1.01
float2 = 2.02
float3 = 3.03
with open("example.txt", "w") as f:
f.write(",".join([str(float1), str(float2), str(float3)]))
Hopefully this article has been useful for you to learn how to write an float to a file in Python.