如何在Python中将浮点数列表输出到二进制文件 [英] How to output list of floats to a binary file in Python

查看:901
本文介绍了如何在Python中将浮点数列表输出到二进制文件的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个Python中的浮点值列表:

  float = [3.14,2.7,0.0,-1.0 ,1.1] 

我想将这些值写入使用IEEE 32位编码的二进制文件。什么是在Python中做到这一点的最好方法?我的列表实际上包含大约200 MB的数据,所以不太慢是最好的。

由于有5个值,我只想要一个20字节的文件作为输出。

解决方案

Alex是绝对正确的,这样做效率更高:

 从数组导入数组
output_file = open('file','wb')
float_array = array('d',[3.14 ,2.7,0.0,-1.0,1.1])$ ​​b $ b float_array.tofile(output_file)
output_file.close()

然后像这样读取数组:

  input_file = open('file',' r')
float_array = array('d')
float_array.fromstring(input_file.read())

array.array 对象也有一个 .fromfile 方法可用于阅读该文件,如果你知道事先计数(例如从文件大小,或其他机制)

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.

解决方案

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', 'r')
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)

这篇关于如何在Python中将浮点数列表输出到二进制文件的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆