Python zipfile

From wikinotes

interact with zipfiles

create

with zipfile.ZipFile('/path/file.zip', 'w') as archive:
    for (root, filenames, dirnames) in os.walk('/some/path'):
        root = root.replace('\\', '/')
        ziproot = root[len(build_dir):]

        if ziproot.startswith('/'):
            ziproot = ziproot[1:]

        for filename in filenames:
            src = '{}/{}'.format(root, filename)
            dst = '{}/{}'.format(ziproot, filename)

        if src != zipfile_name:
            zipfd.write(src, dst)

extract

with zipfile.ZipFile('/path/file.zip', 'r') as archive:
    archive.extractall('/path/to/dstdir')

read

with zipfile.ZipFile('/path/file.zip', 'r') as archive:
    archive.read('file/in/zip')