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)