Python:切片非常大的二进制文件

问题描述 投票:0回答:1

假设我有一个 12GB 的二进制文件,我想从其中切出 8GB。我知道我想要在之间切换的位置索引。

我该怎么做?显然 12GB 不适合内存,那很好,但 8GB 也不适合......我认为这很好,但如果你分块做,二进制似乎不喜欢它!我一次将 10MB 附加到一个新的二进制文件中,新文件中每个 10MB 块的边缘都有不连续性。

有没有一种Python式的方法可以轻松做到这一点?

python binary large-files
1个回答
11
投票

这是一个简单的例子。根据需要进行调整:

def copypart(src, dest, start, length, bufsize=1024*1024):
    with open(src, 'rb') as f1:
        f1.seek(start)
        with open(dest, 'wb') as f2:
            while length:
                chunk = min(bufsize, length)
                data = f1.read(chunk)
                f2.write(data)
                length -= chunk

if __name__ == '__main__':
    GIG = 2**30
    copypart('test.bin', 'test2.bin', 1 * GIG, 8 * GIG)
© www.soinside.com 2019 - 2024. All rights reserved.