Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to output list of floats to a binary file in Python

Tags:

python

file-io

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.

like image 795
Frank Krueger Avatar asked Apr 30 '09 16:04

Frank Krueger


People also ask

How does Python store data in binary file?

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.

Can you write a float to a file in Python?

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 .


1 Answers

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)

like image 68
Nadia Alramli Avatar answered Sep 17 '22 13:09

Nadia Alramli