'How to not include folders when zipping a file using ZipFile in python?

Is there a way to not generate folders during zip? When I extract the zip, it needs to show all the files directly without accessing a folder.

file_paths = utils.get_all_file_paths(path)
with ZipFile("{}/files.zip".format(path), "w") as zip:
    for file in file_paths:
    zip.write(file, os.path.basename(file))

I already tried arcname but it will still generate a folder which is files.

EDIT: My code above will already remove the parent folder. Right now, when I extract the zip file, it will show a folder first with a name same as the zip name. What I want is to zip all the files and when I extract it, it will show all the files directly. Basically, no folders must show during extraction.



Solution 1:[1]

I hope following example will helpful to you

import os
import zipfile

TARGET_DIRECTORY = "../test"
ZIPFILE_NAME = "CompressedDir.zip"

def zip_dir(directory, zipname):
  if os.path.exists(directory):
    outZipFile = zipfile.ZipFile(zipname, 'w', zipfile.ZIP_DEFLATED)

    for dirpath, dirnames, filenames in os.walk(directory):
      for filename in filenames:

        filepath   = os.path.join(dirpath, filename)
        outZipFile.write(filepath)

    outZipFile.close()

if __name__ == '__main__':
  zip_dir(TARGET_DIRECTORY, ZIPFILE_NAME)

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