如何对多个 zip 文件进行上下文管理 BytesIO?

Ste*_*ost 4 python zip bytesio python-3.x

我正在尝试在创建多个 zip 文件时对 BytesIO 流使用上下文管理器。在写入第一个 zip 文件后,我找不到“重置”BytesIO 对象的方法,因此我可以使用相同的 BytesIO 对象创建下一个 zip 文件。在将第二个 zip 文件写入磁盘后尝试打开该文件时,我总是收到“无法打开文件...作为存档”错误。第一个 zip 文件打开得很好。我已经搜索过,但找不到解决方案。将模式从写入更改为追加也没有帮助。当然,我可以重新初始化一个新的 BytesIO 对象,但这会破坏上下文管理器。下面是我认为应该有效的代码。我在 Windows 10 上使用 Anaconda Python 3.6.6。

import io
import os
import zipfile

with io.BytesIO() as bytes_io:
    with zipfile.ZipFile(bytes_io, mode='w') as zf:
        filecount = 0
        for item in os.scandir(r'C:\Users\stephen\Documents'):
            if not item.is_dir():
                zf.write(item.path, item.name)
                filecount += 1
                if filecount % 3 == 0:
                    with open(r'C:\Users\stephen\Documents\\' + str(filecount // 3) + '.zip', 'wb') as f:
                        f.write(bytes_io.getvalue())
                    bytes_io.seek(0)
                    bytes_io.truncate()
Run Code Online (Sandbox Code Playgroud)

blh*_*ing 5

您可以重复使用相同的BytesIO对象,但您应该ZipFile为要创建的每个 zip 文件创建一个新对象:

with io.BytesIO() as bytes_io:
    filecount = 0
    for item in os.scandir(r'C:\Users\stephen\Documents'):
        if not item.is_dir():
            with zipfile.ZipFile(bytes_io, mode='w') as zf:
                zf.write(item.path, item.name)
            filecount += 1
            if filecount % 3 == 0:
                with open(r'C:\Users\stephen\Documents\\' + str(filecount // 3) + '.zip', 'wb') as f:
                    f.write(bytes_io.getvalue())
                bytes_io.seek(0)
                bytes_io.truncate()
Run Code Online (Sandbox Code Playgroud)