Search code examples
pythonzip

Zipping specific files within a folder - not finding zip file


I've got some code that will write specific extension files within a folder to a zip file. Though I continue to run into an error. I've pulled this code from a few different sources. Could I get some help?

ext = [".shp", ".shx", ".prj", ".cpg", ".dbf"]
# compress shapefile and name it the ortho name
for folder, subfolder, files in os.walk('D:/combined_shape'):
    for file in files:
        if file.endswith(tuple(ext)):
            zipfile.ZipFile('D:/combined_shape/' + 'compiled' + '/.zip', 'w').write(os.path.join(folder, file),
                               os.path.relpath(os.path.join(folder, file),
                                               'D:/combined_shape/'), compress_type = zipfile.ZIP_DEFLATED)
Traceback (most recent call last):
  File "D:/PycharmProjects/Augmentation/merge_shp.py", line 30, in <module>
    zipfile.ZipFile('D:/combined_shape/' + 'compiled' + '/.zip', 'w').write(os.path.join(folder, file),
  File "D:\PyCharmEnvironments\lib\zipfile.py", line 1240, in __init__
    self.fp = io.open(file, filemode)
FileNotFoundError: [Errno 2] No such file or directory: 'D:/combined_shape/compiled/.zip'

EDITS Directory Zip Directory


Solution

  • The "File or directory not found" error is because of /.zip in the name of the zip file. The / should be removed.

    The problem with only getting one file in the archive is the use of w mode when opening the ZipFile. As it states in the documentation:

    'w' to truncate and write a new file

    So for each file you want to add it's first removing all the files that were added previously.

    Open the file once before the loop, then add each file to it.

    with zipfile.ZipFile('D:/combined_shape/compiled.zip', 'w') as z:
        for folder, subfolder, files in os.walk('D:/combined_shape'):
            for file in files:
                if file.endswith(tuple(ext)):
                    z.write(os.path.join(folder, file),
                            os.path.relpath(os.path.join(folder, file),
                                            'D:/combined_shape/'), 
                            compress_type = zipfile.ZIP_DEFLATED)