简体   繁体   中英

Python to create multiple zip files for all in a folder

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)
        ZipFile.close()

The generated zip files contains also the paths, ie 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?

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))

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM