Search code examples
pythonziprelative-pathbytesio

how to use zip.write() on directories using a relative path in python?


I am wanting to add explicit entries for the directories in my zipfile. For example my zipfile includes:

assets/images/logo.png

When in reality I need it to include:

assets/
assets/images/
assets/images/logo.png

So my question is, how do I add the directories as explicit entries using relative paths? I tried to use zip.write(relative/path/to/directory) but it says it can't find the directory, since its a relative path. It works when I put

/Users/i510118/Desktop/Engineering/kit-dev-portal-models/src/kit_devportal_models/static_data/static_extension/created_extnsn_version_update2/assets/images/logo.png

inside of zipfile.write(), but I need it to just be the relative path, which is just

assets/images/logo.png

is this possible?

Here is my full code

        buf = io.BytesIO()
    zipObj = zipfile.ZipFile(buf, "w")
    extension_folder = "created_extnsn_version_update2"
    with zipObj:
        # Iterate over all the files in directory
        for folderName, subfolders, filenames in os.walk(path_to_extension_directory):
            # If the folder is not the root folder the extension is in
            if not folderName.endswith(extension_folder):
                folder = folderName.split(f"{extension_folder}/", 1)[1]
            else:
                folder = ''
            for filename in filenames:
                # create complete filepath of file in directory
                filePath = os.path.relpath(os.path.join(folderName, filename), path_to_extension_directory)
                with open(f"{folderName}/{filename}", 'rb') as file_data:
                    bytes_content = file_data.read()
                    # Add folder to zip if its not the root directory
                    if folder:
                        zipObj.write(folder)
                    # Add file to zip
                    zipObj.writestr(filePath, bytes_content)
                    # edit zip file to have all permissions
                    zf = zipfile.ZipFile(buf, mode='a')
                    info = zipfile.ZipInfo(f"{folderName}/{filename}")
                    info.external_attr = 0o777 << 16
                    zf.writestr(info, f"{folderName}/{filename}")

    # Rewind the buffer's file pointer (may not be necessary)
    buf.seek(0)
    return buf.read()

Please let me know if you need more information!


Solution

  • From code stolen from add empty directory using zipfile?

    import zipfile
    
    zf = zipfile.ZipFile('test.zip', 'w')
    
    folders = [
        "assets/",
        "assets/images/",
        ]
    
    for n in folders:
        zfi = zipfile.ZipInfo(n)
        zf.writestr(zfi, '')
    
    zf.write('logo.png', 'assets/images/logo.png')
    
    zf.close()
    
    zf = zipfile.ZipFile('test.zip', 'r')
    
    for i in zf.infolist():
        print(f"is_dir: {i.is_dir()}; filename: {i.filename}")
    
    zf.close()