Python 2.6.6 的 zip 创建问题

zip creation issue with Python 2.6.6

我有使用 python 2.6.6 创建 test.zip 的代码,如下所示,并创建了一个 zip。

但在 test.zip 里面我可以看到另一个 test.zip,大小为 0/1 MB。我不确定如何修复或缺少什么。

def createZip(path, ziph):
    # ziph is zipfile handle
    for folder, subfolders, files in os.walk(path):
        for file in files:
            ziph.write(os.path.join(folder, file), os.path.relpath(os.path.join(folder,file),path), compress_type = zipfile.ZIP_DEFLATED)


zipf = zipfile.ZipFile('/home/stbUpgrade/tmp/downLoad/test.zip', 'w')
createZip('/home/stbUpgrade/tmp/downLoad/', zipf)
zipf.close()

您将文件夹压缩到一个文件中,该文件是该文件夹的一部分。 zipfile.ZipFile() 将创建一个空的 zip 文件,因此您在 test.zip.

中得到一个空的 zip 文件

您应该将 test.zip 放入压缩文件夹之外的文件夹中(例如 tmp 文件夹)。

顺便说一句:如果出现错误,您应该使用 with

with zipfile.ZipFile('/home/stbUpgrade/tmp/test.zip', 'w') as zipf:
    createZip('/home/stbUpgrade/tmp/downLoad/', zipf)