Using zipfile to create a zip file with directories and files inside those directories

Michael Torrie torriem at gmail.com
Fri Mar 6 22:06:40 EST 2020


I am trying to do something very simple but having no success in finding
out how to do it. I just want to use the Python zipfile module to create
a zip file with a specific directory structure and create and write to
files inside those subdirectories (not files already on disk).  The
documentation talks about writing files from disk, but I'm interested in
creating these files from within Python directly in the zip archive.
I've read over the docs several times but nothing speaks to this, and
none of the examples I've searched for show this either.

I thought that in zip files, directories are really just part of the
name of the file, and if unless you tell unzip not to, it creates them
as files are extracted. So I naively thought I could use the "open"
method of zipfile, giving it a relative path describing the relative
path and file name that I want to then write bytes to.  But seems I am
mistaken.  Is this a limitation of the zip format that cannot allow that
sort of thing?  Must I resort to temporary files?

Plenty of examples on how to create an archive from existing files and
directories on disk of course, which isn't what I want to do.



More information about the Python-list mailing list