python 读取写入二进制文件
程序员文章站
2022-06-12 16:28:42
...
python 读取,储存二进制文件
import struck
def load_array(file, big=False):
"""
从二进制文件中加载二维数组并返回
:param big:
:param file:
:return:
"""
# print('load binary data from %s' % file)
f = open(file, 'rb+')
c = f.read()
# c = zlib.decompress(c)
if big:
data = struct.unpack(('>%df' % (len(c) / 4)), c)
else:
data = struct.unpack(('%df' % (len(c) / 4)), c)
return list(data)
def save_array(array, path):
"""
将二维浮点数组保存到二进制文件上
:param array:
:param file:
:return:
"""
dir_name = os.path.split(path)[0]
data = struct.pack(('%df' % len(array)), *array)
if not os.path.exists(dir_name):
os.makedirs(dir_name)
if os.path.exists(path):
os.remove(path)
f = open(path, 'wb+')
# c = zlib.compress(data)
f.write(data)
f.close()