5
4

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 5 years have passed since last update.

Python - Zip , Unzip File with python 3

Posted at

#INTRODUCTION
Hey guys! How have you been doing? I hope you are doing good :). Ok, Let get into our today topic. Recently , I have been working on the python project which related to Compression , Extracting file and I think it is a useful function of python so I want to share it with you.Ok, Let's get started.

#GET STARTED

###1. Zip File

Many people when they are working with Zip file , they only use Python zipFile Library. But today I will introduce you to another library which is shutil. It is really simple and easy to compress a file.

Example

Before is my project structure.

Screen Shot 2018-06-06 at 10.50.44 AM.png

let say , I want to zip the .txt file. We can do it like this (see below code)

import shutil

zipOutputName = "archive"
fileType = "zip"
path = "./testZip"
fileName = "XN92RSUKPS.txt"

shutil.make_archive(zipOutputName,fileType,path,fileName)
  1. First you need to import shutil Library
  2. zipOutputName : is the output name of your zip file.
  3. fileType : type of compression.
  4. path : the path to the file or directory
  5. fileName : file that we need to zip.

We also can zip the whole directory (see below code)

import shutil

zipOutputName = "archive"
fileType = "zip"
path = "."
fileName = "testZip"

shutil.make_archive(zipOutputName,fileType,path,fileName)

###2. Unzip File
Ok, after we learn how to compress file. Now it time to learn how to extract file. This time we will use zipFile library.


import zipfile

zipfilePath = ("./archive.zip")
zip = zipfile.ZipFile(zipfilePath)
zip.extractall(".")
zip.close()
  1. So to unzip , first we import zipfile library
  2. Then we need to provide file / directory path.
  3. after that we give the output path to extractall method.
5
4
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
5
4

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?