如何在 Python 中复制一个二进制文件块?
How do I copy a chunk of a binary file in Python?
我有一个很大的二进制文件 (60GB),我想将其拆分成几个较小的文件。我遍历了文件并找到了我想要使用 fileObject.tell()
方法拆分文件的点,所以现在我有一个名为 file_pointers
的包含 1000 个拆分点的数组。我正在寻找一种从这些分割点创建文件的方法,所以函数看起来像:
def split_file(file_object, file_pointers):
# Do something here
它会为每个块创建文件。我看到了这个question,但我担心Python的循环可能太慢了,我也觉得一定有某种内置函数应该有类似的东西。
这比我想象的要简单得多,但我会 post 在这里回答,以防有人需要快速解决方案。这是从 file_pointer[1]
复制到 file_pointer[2]
的示例
with open('train_example.bson', 'rb') as fbson:
fbson.seek(file_pointers[1])
bytes_chunk = fbson.read(file_pointers[2] - file_pointers[1])
with open('tmp.bson', 'wb') as output_file:
output_file.write(bytes_chunk)
我有一个很大的二进制文件 (60GB),我想将其拆分成几个较小的文件。我遍历了文件并找到了我想要使用 fileObject.tell()
方法拆分文件的点,所以现在我有一个名为 file_pointers
的包含 1000 个拆分点的数组。我正在寻找一种从这些分割点创建文件的方法,所以函数看起来像:
def split_file(file_object, file_pointers):
# Do something here
它会为每个块创建文件。我看到了这个question,但我担心Python的循环可能太慢了,我也觉得一定有某种内置函数应该有类似的东西。
这比我想象的要简单得多,但我会 post 在这里回答,以防有人需要快速解决方案。这是从 file_pointer[1]
复制到 file_pointer[2]
with open('train_example.bson', 'rb') as fbson:
fbson.seek(file_pointers[1])
bytes_chunk = fbson.read(file_pointers[2] - file_pointers[1])
with open('tmp.bson', 'wb') as output_file:
output_file.write(bytes_chunk)