0

I am working with the following folder structure:

.
+-- temp
|   +-- sample1.csv
|   +-- sample2.csv
+-- zips
|   +-- zip1.zip
|   +-- zip2.zip
+-- main.py

I want to zip the contents of the temp folder into a zip file, but I do not want to include the folder. I have tried the following (expecting to compress only the files):

import pathlib
import zipfile

origin = pathlib.Path('.') / 'temp'
destination = pathlib.Path('.') / 'zips' / 'zip3.zip'

with zipfile.ZipFile(destination, mode='w') as zipfile_:
    for content in origin.iterdir():
        zipfile_.write(content)

I also tried using shutil.make_archive(), but it rendered the same result, the only diference being that the directory was simply named ".".


EDIT: Thank you CookieReaver and metatoaster (I believe) for pointing out that ZipFile.write() method has an argument called arcname that will name the file (ZipFile.write() documentation).

Here is my original question with the fix applied:

import pathlib
import zipfile

origin = pathlib.Path('.') / 'temp'
destination = pathlib.Path('.') / 'zips' / 'zip3.zip'

with zipfile.ZipFile(destination, mode='w') as zipfile_:
    for content in origin.iterdir():
        zipfile_.write(content, content.name)

1 Answers1

0
import zipfile
import os

orig = r"path_to_origin_dir"
dest = r"path_to_destination_dir"

zip_name = "zip3.zip"
target_zip = zipfile.ZipFile(os.path.join(dest, zip_name), 'w')

for dp, dn, fn in os.walk(orig):

    for filename in fn:
        if filename.endswith('csv'):
            target_zip.write(os.path.join(dp, filename), os.path.relpath(os.path.join(dp, filename), orig))

target_zip.close()

Is this what you're aiming for?

Joonyoung Park
  • 474
  • 3
  • 6