Using Python to add a list of files into a zip file

original answered Sep 2 '14 at 3:52

according to the guidance above, the final is: (just putting them together in case it could be useful)

import zipfile
import os

working_folder = 'C:\\Python27\\'

files = os.listdir(working_folder)

files_py = []

for f in files:
    if f.endswith('py'):
        fff = os.path.join(working_folder, f)
        files_py.append(fff)

ZipFile = zipfile.ZipFile("zip testing3.zip", "w" )

for a in files_py:
    ZipFile.write(os.path.basename(a), compress_type=zipfile.ZIP_DEFLATED)
ZipFile.close()

added in Mar 2020 enlightened by @jinzy at zip file and avoid directory structure, the last line of above changed to below to avoid file structures in the zip file.

ZipFile.write(a, "C:\\" + os.path.basename(a), compress_type=zipfile.ZIP_DEFLATED)

You need to pass in the compression type as a keyword argument:

ZipFile.write(a, compress_type=zipfile.ZIP_DEFLATED)

Without the keyword argument, you are giving ZipFile.write() an integer arcname argument instead, and that is causing the error you see as the arcname is being normalised.

Tags:

Python

Zipfile