1

I am trying to use zipfile to zip several files together into a single .zip file. The files I need to zip are not in the root folder from which the python script runs, so i have to specify the path when adding a file to the zip. The problem is that I end up with a folder structure in the zip file, i really only want each file and not the folders. so..

zip = zipfile.ZipFile('./tmp/afile.zip', 'w')
zip.write('./tmp/file1.txt')
zip.write('./tmp/items/file2.txt')

results in a zip files that extracts to:

.
|
|-tmp
|  |file.txt
|  |-items
|  |  file2.txt

Is there any way to just add the files to the "root" of the zip file and not creature the folders?

Dharman
  • 30,962
  • 25
  • 85
  • 135
  • I think this problem was already on Stackoverflow. If I'm not wrong then you can use `zip.write(filename_to_compress, expected_name_in_zip)` – furas May 05 '21 at 21:49
  • @furas if the problem is already on stack, flag this as a duplicate in reference to that question. – Libra May 05 '21 at 21:50
  • @Laif first I would have to find previous question - I only remeber that I answered it long, long time ago – furas May 05 '21 at 21:52
  • @furas > Your profile > answers > ctrl+f "zip" – Libra May 05 '21 at 21:52
  • 2
    Does this answer your question? [ZIp only contents of directory, exclude parent - Python](https://stackoverflow.com/questions/42055873/zip-only-contents-of-directory-exclude-parent-python) – Libra May 05 '21 at 21:53
  • @Laif it was long, long time ago - I don't find it on first page but rather on 20, 30 or maybe 50 – furas May 05 '21 at 21:53
  • @furas it ws on page 3 haha – Libra May 05 '21 at 21:54
  • @furas good decision to close, mind if I add my answer to yours to show the usage with pathlib? – Umar.H May 05 '21 at 21:56
  • @Laif I expected it was much older question :) If you have intersting answer then add it. – furas May 05 '21 at 21:57
  • @furas You had the answer, this question is a duplicate so nobody should answer it – Libra May 05 '21 at 21:58
  • @furas this works, thanks. - zip.write(filename_to_compress, expected_name_in_zip) – Seth.Beauchamp May 05 '21 at 22:06

1 Answers1

1

try with Pathlib which returns a posix object with various attributes.

Also I would caution you about using zip as a variable as that's a key function in python

from pathlib import Path
from zipfile import ZipFile

zipper = ZipFile('afile.zip', 'w')

files = Path(root).rglob('*.txt') #get all files.
for file in files:
    zipper.write(file,file.name)

enter image description here


enter image description here

Umar.H
  • 22,559
  • 7
  • 39
  • 74