How to compress and decompress folders in ZIP format using Python

Published:  

python


This is a method of compressing a folder into a ZIP file (.zip) with Python.
It also describes how to unzip a ZIP file.

Environment

  • Windows 10
  • Python 3.6.2

Compress to ZIP format

from shutil import make_archive

make_archive('data', 'zip', root_dir='./data')

Use make_archive of shutil module.

  • The first argument specifies the file name to be created without the extension.
  • The second argument specifies the compression format.
    (In the above example, the first argument is 'data' and the second argument is'zip', so the created file is data.zip.)
  • root_dir specifies the folder you want to compress.

In addition to zip, 'tar','gztar', 'bztar','xztar' can be used as the compression format.

Unzip ZIP file

from shutil import unpack_archive

unpack_archive('./data.zip', extract_dir='./unpacked_data', format='zip')

Use unpack_archive of shutil module.

  • The first argument specifies the file name you want to decompress.
  • extract_dir specifies the name of the folder to extract.
  • format specifies the file format. If omitted, it will be judged from the file extension.

Finally

Python also has a module called zipfile that can handle files in ZIP format. If you want to use it in detail, I think you will use it.
If you just want to compress the folder (or decompress the file), I think the method introduced here is simple.



Related Posts