简体   繁体   English

Python Windows 上的 zipfile 问题

[英]Python zipfile issue on Windows

I wrote a simple, rough program that automatically zip everything inside the current working directory.我写了一个简单粗略的程序,自动 zip 当前工作目录中的所有内容。 It works very well on Linux but there is huge problem when running on Windows.它在 Linux 上运行良好,但在 Windows 上运行时存在巨大问题。

Here is my code:这是我的代码:

import os, zipfile

zip = zipfile.ZipFile('zipped.zip', 'w')  #Create a zip file
zip.close()

zip = zipfile.ZipFile('zipped.zip', 'a')  #Make zip file append instead of overwriting
for dir, subdir, file in os.walk(os.path.relpath('.')):  #Loop for walking thru the directory

    for subdirectory in subdir:
        subdirs = os.path.join(dir, subdirectory)  
        zip.write(subdirs, compress_type=zipfile.ZIP_DEFLATED)

    for files in file:
        fil = os.path.join(dir, files)
        zip.write(fil, compress_type=zipfile.ZIP_DEFLATED)

zip.close()

When I ran this on Windows, it won't stop compressing, but infinitely create the "zipped.zip" file in the zipped file, after left it running a few seconds, generated few hundreds MB of file.当我在 Windows 上运行它时,它不会停止压缩,而是在压缩文件中无限创建“zipped.zip”文件,让它运行几秒钟后,生成几百 MB 的文件。 On Linux, the program will stop after it zipped all the files excluding newly created zipped.zip.在 Linux 上,程序将在压缩所有文件后停止,不包括新创建的 zipped.zip。

Screenshot: A "zipped.zip" inside the "zipped.zip"截图:“zipped.zip”里面的一个“zipped.zip”

I am wondering did I miss some code that will make this works well on Windows?我想知道我是否遗漏了一些代码可以使它在 Windows 上运行良好?

I would zip the folder in a temporary zipfile, then move the temporary zipfile in the folder.我将 zip 临时压缩文件中的文件夹,然后将临时压缩文件移动到该文件夹中。

That seems to be because you are saving the zip to the same folder that you are trying to compress, and that must be confusing os.walk() somehow.这似乎是因为您将 zip 保存到您尝试压缩的同一文件夹中,这一定会使os.walk()不知何故混淆。

One possible solution, as long as you don't have a giant directory to compress, is to use os.walk() to build a full list of what will be compressed, and after the list is complete, then you would it to populate the zip, instead of using os.walk() directly.一种可能的解决方案是,只要您没有要压缩的巨大目录,就是使用os.walk()构建将要压缩的内容的完整列表,在列表完成后,您将填充它zip,而不是直接使用os.walk()

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM