#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.
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)
- First you need to import shutil Library
- zipOutputName : is the output name of your zip file.
- fileType : type of compression.
- path : the path to the file or directory
- 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()
- So to unzip , first we import zipfile library
- Then we need to provide file / directory path.
- after that we give the output path to extractall method.