将多个 numpy 数组流式传输到一个文件

dtr*_*ers 6 python arrays file-io numpy binaryfiles

这与将多个 numpy 数组写入文件不同,因为我需要能够流式传输内容,而不是一次全部写入。

我需要将多个压缩的 numpy 二进制数组写入一个文件。在写入之前我无法将所有数组存储在内存中,因此它更像是将 numpy 数组流式传输到文件中。

这目前作为文本工作正常

file = open("某个文件")

在做东西时: file.writelines(somearray + "\n") 其中一些数组是每个循环的新实例

但是,如果我尝试将数组写为二进制,这将不起作用。

数组以 30hz 创建,并且变得太大而无法保存在内存中。它们也不能每个都存储到一堆单个数组文件中,因为那样会很浪费并且会造成很大的混乱。

所以我希望每个会话只需要一个文件,而不是每个会话 10k 个文件。

Seb*_*ian 3

一种选择可能是使用 pickle 将数组保存到作为文件打开的文件中append binary

import numpy as np
import pickle
arrays = [np.arange(n**2).reshape((n,n)) for n in range(1,11)]
with open('test.file', 'ab') as f:
    for array in arrays:
        pickle.dump(array, f)

new_arrays = []        
with open('test.file', 'rb') as f:
    while True:
        try:
            new_arrays.append(pickle.load(f))
        except EOFError:
            break
assert all((new_array == array).all() for new_array, array in zip(new_arrays, arrays))
Run Code Online (Sandbox Code Playgroud)

这可能不是最快的,但应该足够快了。看起来这会占用更多数据,但比较这些:

x = 300
y = 300
arrays = [np.random.randn(x, y) for x in range(30)]

with open('test2.file', 'ab') as f:
    for array in arrays:
        pickle.dump(array, f)

with open('test3.file', 'ab') as f:
    for array in arrays:
        f.write(array.tobytes())

with open('test4.file', 'ab') as f:
    for array in arrays:
        np.save(f, array)
Run Code Online (Sandbox Code Playgroud)

您会发现文件大小分别为 1,025 KB、1,020 KB 和 1,022 KB。