Tahreem Iqbal
Tahreem Iqbal

Reputation: 1015

Create zip archive with multiple files

I'm using following code where I pass .pdf file names with their paths to create zip file.

for f in lstFileNames:
        with zipfile.ZipFile('reportDir' + str(uuid.uuid4()) + '.zip', 'w') as myzip:
            myzip.write(f)

It only archives one file though. I need to archive all files in my list in one single zip folder.

Before people start to point out, yes I have consulted answers from this and this link but the code given there doesn't work for me. The code runs but I can't find generated zip file anywhere in my computer.

A simple straightforward answer would be appreciated. Thanks.

Upvotes: 25

Views: 17863

Answers (2)

fastap
fastap

Reputation: 13

To prevent including the entire file path as Helen Neely mentioned in the comment, one can use the arcname parameter as follows:

from pathlib import Path

with zipfile.ZipFile('reportDir' + str(uuid.uuid4()) + '.zip', 'w') as myzip:
    for f in lstFileNames:   
        myzip.write(f, arcname=Path(f).name)

Upvotes: 1

Sardorbek Imomaliev
Sardorbek Imomaliev

Reputation: 15370

Order is incorrect. You are creating new zipfile object for each item in lstFileNames

Should be like this.

with zipfile.ZipFile('reportDir' + str(uuid.uuid4()) + '.zip', 'w') as myzip:
    for f in lstFileNames:   
        myzip.write(f)

Upvotes: 45

Related Questions