zip and Unzip in Python

Posted October 18, 2022 by Rohith ‐ 1 min read

zip is used to compress the file. unzip is used to decompress the compressed file. In this article we will zip and unzip operation in python.

We use python modules gzip and shutil to compress and decompress the files. gzip module is used in compressing and decompressing files whereas shutil is used to copy the decompressed file to a new file.

Zip & Unzip By Example

Lets compression and decompression with python example.

Compression Using Python gzip Module

  • Without using with
import gzip

content = 'whiletrue.live is awesome!'
f = gzip.open('/tmp/file.txt.gz', 'wb')
f.write(content)
f.close()
  • Using with
import gzip

content = 'whiletrue.live is awesome!'
with open('/tmp/file.txt.gz', 'wb') as f:
    f.write(content)

Decompress Using Python gzip Module

  • without using with
import gzip
import shutil

gz_file = gzip.open('file.txt.gz', 'rb')
uncompressed_file = open('file.txt', 'wb')
shutil.copyfileobj(gz_file, uncompressed_file)

gz_file.close()
uncompressed_file.close()
  • without using with
import gzip
import shutil
with gzip.open('file.txt.gz', 'rb') as f_in, with open('file.txt', 'wb') as f_out:
    shutil.copyfileobj(f_in, f_out)
quick-references python gzip blog

Subscribe For More Content