Reputation:
Given the directory at a path a:\\b\\c\\d\\e
, I want to create a zipfile in python 3.5+ that looks like this:
file.zip # want this
+d
+-...files from d\
+-e
+-...files from e\
I tried this by walking the target path like this, using os
and zipfile
:
start_path = "a:\\b\\c\\d"
for root, dirs, files in os.walk(start_path):
for file in files:
ziph.write(os.path.relpath(os.path.join(root, file)))
Due to the the relpath
and working dir being in b
, the code will create a zip file as follows:
file.zip # do not want this
+c
+-...files from c\
+-d
+-...files from d\
+-e
+-...files from e\
My Question is: How can I force the zipwriter to create a directory structure as shown at the beginning, starting with dir d
while I know the full path only at runtime.
Upvotes: 1
Views: 1238
Reputation: 5948
ZipFile.write
accepts a second parameter, which is the directory you want it to be in inside the zip
. So you can have something like:
start_path = "a:\\b\\c\\d"
import os
zip_start_path = start_path.split(os.sep)[-1]
Upvotes: 1