HiveBrain v1.2.0
Get Started
← Back to all entries
snippetpythonCritical

How to create a zip archive of a directory?

Submitted by: @import:stackoverflow-api··
0
Viewed 0 times
howdirectoryarchivezipcreate

Problem

How can I create a zip archive of a directory structure in Python?

Solution

As others have pointed out, you should use zipfile. The documentation tells you what functions are available, but doesn't really explain how you can use them to zip an entire directory. I think it's easiest to explain with some example code:
import os
import zipfile

def zipdir(path, ziph):
# ziph is zipfile handle
for root, dirs, files in os.walk(path):
for file in files:
ziph.write(os.path.join(root, file),
os.path.relpath(os.path.join(root, file),
os.path.join(path, '..')))

with zipfile.ZipFile('Python.zip', 'w', zipfile.ZIP_DEFLATED) as zipf:
zipdir('tmp/', zipf)

Context

Stack Overflow Q#1855095, score: 727

Revisions (0)

No revisions yet.