使用Python将zip文件分成多个块

3

我有一段代码可以成功创建zip文件,但如果文件大小超过1MB,我需要将其拆分。

我有以下代码,但它无法工作:

    from split_file_reader.split_file_writer import SplitFileWriter
    import zipfile

    # make element tree
    tree = etree.ElementTree(batch_element)

    # make xml file and write it in stream
    xml_object = BytesIO()
    tree.write(xml_object, pretty_print=True, xml_declaration=False, encoding="utf-8")
    xml_file = xml_object.getvalue()

    final = BytesIO()

    with SplitFileWriter(final, 1_000_000) as sfw:
        with zipfile.ZipFile(sfw, "a") as zip_file:
            zip_file.writestr('Batch.xml', xml_file)

我想以字节形式检索分割文件。 压缩部分工作正常,但分割不起作用。


2
你似乎正在使用https://pypi.org/project/split-file-reader/;可能是为了在你的问题中包含这些信息。 - undefined
2个回答

2
根据split_file_reader文档SplitFileWriter的第一个参数可以是生成文件对象的生成器。这将允许您将zip文件拆分为BytesIO块列表。
以下是一个可行的示例脚本:
import zipfile
from io import BytesIO
from lxml import etree
from split_file_reader.split_file_writer import SplitFileWriter

# make element tree
# tree = etree.ElementTree(batch_element)
tree = etree.parse('/tmp/test.xml')

# make xml file and write it in stream
xml_object = BytesIO()
tree.write(xml_object, pretty_print=True, xml_declaration=False, encoding="utf-8")
xml_file = xml_object.getvalue()

chunks = []

def gen(lst):
    while True:
        lst.append(BytesIO())
        yield lst[-1]

with SplitFileWriter(gen(chunks), 1_000_000) as sfw:
    with zipfile.ZipFile(sfw, "w") as zip_file:
        zip_file.writestr('Batch.xml', xml_file)

for i, chunk in enumerate(chunks):
    print(f'chunk {i}: {len(chunk.getvalue())}')

输出:

chunk 0: 1000000
chunk 1: 1000000
chunk 2: 1000000
chunk 3: 1000000
chunk 4: 1000000
chunk 5: 887260

1
这里是文档的已更正链接:https://gitlab.com/Reivax/split_file_reader/-/tree/master/src/split_file_writer#arguments。包结构已经改变。我是这个项目的作者,这是一个可接受的答案。你也可以永远使用相同的BytesIO对象,并在每次截断时简单地对其进行后处理,在BytesIO填充后立即在生成器中执行后处理,而不是在完整文件写入后执行,从而节省内存。 - undefined

1

阅读您正在使用的模块的文档,该模块是 https://pypi.org/project/split-file-reader

它应该包含使用说明。

编辑:这是一个示例:

with SplitFileWriter("split.zip.", 500_000) as sfw:
    with zipfile.ZipFile(file=sfw, mode='w') as zipf:
        for root, dirs, files in os.walk("./"):
            for file in files:
                if file.startswith("random_payload"):
                    zipf.write(os.path.join(root, file))

我看过文档,但内容不多。因为这是一个新的库。在这个例子中,它只是简单地将文件保存在某个位置,但我想将其作为字节变量检索出来。 - undefined

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接