I have a list of floating-point values in Python:
floats = [3.14, 2.7, 0.0, -1.0, 1.1]
I would like to write these values out to a binary file using IEEE 32-bit encoding. What is the best way to do this in Python? My list actually contains about 200 MB of data, so something "not too slow" would be best.
Since there are 5 values, I just want a 20-byte file as output.
First, open a file in binary write mode and then specify the contents to write in the form of bytes. Next, use the write function to write the byte contents to a binary file.
To write float values to a file in Python, we can use formatted strings. Formatted strings are special strings in Python that allow us to insert string representations of objects inside strings. Unlike regular strings, the formatted strings are prefixed with an f .
Alex is absolutely right, it's more efficient to do it this way:
from array import array output_file = open('file', 'wb') float_array = array('d', [3.14, 2.7, 0.0, -1.0, 1.1]) float_array.tofile(output_file) output_file.close()
And then read the array like that:
input_file = open('file', 'rb') float_array = array('d') float_array.fromstring(input_file.read())
array.array
objects also have a .fromfile
method which can be used for reading the file, if you know the count of items in advance (e.g. from the file size, or some other mechanism)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With