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

musbur at posteo.org musbur at posteo.org
Sat Mar 7 03:08:58 EST 2020


On Fri, 6 Mar 2020 20:06:40 -0700
Michael Torrie <torriem at gmail.com> wrote:

> The documentation talks about writing files from
> disk, but I'm interested in creating these files from within Python
> directly in the zip archive.

But you have seen writestr(), haven't you?

ZipFile.writestr(zinfo_or_arcname, data, compress_type=None,
compresslevel=None)

    Write a file into the archive. The contents is data, which may be
    either a str or a bytes instance; 
	
> 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.

No your're not. writestr() and ZipInfo are your friends, unless I
haven't understood what you're trying to do.


More information about the Python-list mailing list