I’m trying to create a function in my script that zips the contents of a given source directory (src) to a zip file (dst). For example, zip('/path/to/dir', '/path/to/file.zip'), where /path/to/dir is a directory, and /path/to/file.zip doesn’t exist yet. I do not want to zip the directory itself, this makes all the difference in my case. I want to zip the files (and subdirs) in the directory. This is what I’m trying:
def zip(src, dst):
zf = zipfile.ZipFile("%s.zip" % (dst), "w")
for dirname, subdirs, files in os.walk(src):
zf.write(dirname)
for filename in files:
zf.write(os.path.join(dirname, filename))
zf.close()
This creates a zip that is essentially /. For example, if I zipped /path/to/dir, extracting the zip creates a directory with “path” in it, with “to” in that directory, etc.
Does anyone have a function that doesn’t cause this problem?
I can’t stress this enough, it needs to zip the files in the directory, not the directoy itself.
The
zipfile.write()method takes an optionalarcnameargumentthat specifies what the name of the file should be inside the zipfile.
You can use this to strip off the path to
srcat the beginning. Here Iuse
os.path.abspath()to make sure that bothsrcand thefilename returned by
os.walk()have a common prefix.With a directory structure like this:
The script prints:
And the contents of the resulting zip file are: