'How to zip files without including the folder they are in? [duplicate]

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?



Solution 1:[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

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 Umar.H