Many files in a folder. I want to zip them all. Every 10 files will be added to a zip file.

import os, glob
import numpy as np
import zipfile

file_folder = "C:\\ABC\\DEF\\"

all_files = glob.glob(file_folder + "/*.*")

several_lists= np.array_split(all_files, 10)

for num, file_names in enumerate(several_lists):
    ZipFile = zipfile.ZipFile(file_folder + str(num) + ".zip", "w" )

    for f in file_names:
        ZipFile.write(f, compress_type=zipfile.ZIP_DEFLATED)

The generated zip files contains also the paths, i.e. every zip file has a folder DEF in a folder ABC. The file themselves are in DEF.

I changed the line to:

ZipFile.write(os.path.basename(f), compress_type=zipfile.ZIP_DEFLATED)

Error pops for:

WindowsError: [Error 2] The system cannot find the file specified:

How to correct it? Thank you.

Btw, is there a big difference in zip and rar file created by Python?

1 Answers

Masklinn On Best Solutions

ZipFile.write has a parameter arcname which allows explicitly providing an in-archive filename (by default it's the same as the on-disk path).

So just use zip.write(f, arcname=os.path.basename(f)).

Also for simplicity you could set the compression mode on the zipfile.ZipFile.

edit: and you can use the zipfile as a context manager for more reliability and less lines, and assuming Python 3.6 f-strings are nice:

with zipfile.ZipFile(f'{file_folder}{num}.zip', 'w', compression=zipfile.ZIP_DEFLATED) as zip:
    for f in file_names:
        zip.write(f, arcname=os.path.basename(f))