python – How to create a zip archive of a directory?
python – How to create a zip archive of a directory?
The easiest way is to use shutil.make_archive
. It supports both zip and tar formats.
import shutil
shutil.make_archive(output_filename, zip, dir_name)
If you need to do something more complicated than zipping the whole directory (such as skipping certain files), then youll need to dig into the zipfile
module as others have suggested.
As others have pointed out, you should use zipfile. The documentation tells you what functions are available, but doesnt really explain how you can use them to zip an entire directory. I think its 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, ..)))
zipf = zipfile.ZipFile(Python.zip, w, zipfile.ZIP_DEFLATED)
zipdir(tmp/, zipf)
zipf.close()
python – How to create a zip archive of a directory?
To add the contents of mydirectory
to a new zip file, including all files and subdirectories:
import os
import zipfile
zf = zipfile.ZipFile(myzipfile.zip, w)
for dirname, subdirs, files in os.walk(mydirectory):
zf.write(dirname)
for filename in files:
zf.write(os.path.join(dirname, filename))
zf.close()