Adding folders to a zip file using python
Ok, after i understood what you want, it is as simple as using the second argument of zipfile.write
, where you can use whatever you want:
import zipfilemyZipFile = zipfile.ZipFile("zip.zip", "w" )myZipFile.write("test.py", "dir\\test.py", zipfile.ZIP_DEFLATED )
creates a zipfile where test.py
would be extracted to a directory called dir
EDIT:I once had to create an empty directory in a zip file: it is possible.after the code above just delete the file test.py from the zipfile, the file is gone, but the empty directory stays.
A zip file has no directory structure, it just has a bunch of pathnames and their contents. These pathnames should be relative to an imaginary root folder (the ZIP file itself). "../" prefixes have no defined meaning in a zip file.
Consider you have a file, a
and you want to store it in a "folder" inside a zip file. All you have to do is prefix the filename with a folder name when storing the file in the zipfile:
zipi= zipfile.ZipInfo()zipi.filename= "folder/a" # this is what you wantzipi.date_time= time.localtime(os.path.getmtime("a"))[:6]zipi.compress_type= zipfile.ZIP_DEFLATEDfiledata= open("a", "rb").read()zipfile1.writestr(zipi, filedata) # zipfile1 is a zipfile.ZipFile instance
I don't know of any ZIP implementations allowing the inclusion of an empty folder in a ZIP file. I can think of a workaround (storing a dummy filename in the zip "folder" which should be ignored on extraction), but not portable across implementations.