'Python zipfile issue on Windows

I wrote a simple, rough program that automatically zip everything inside the current working directory. It works very well on Linux but there is huge problem when running on 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. On Linux, the program will stop after it zipped all the files excluding newly created zipped.zip.

Screenshot: A "zipped.zip" inside the "zipped.zip"

I am wondering did I miss some code that will make this works well on Windows?



Solution 1:[1]

I would zip the folder in a temporary zipfile, then move the temporary zipfile in the folder.

Solution 2:[2]

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.

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.

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 Gribouillis
Solution 2 Haroldo_OK