Python Tutorial Compressing and Extracting Files Using ZipFile Library Full Project

Python Tutorial Compressing and Extracting Files Using ZipFile Library Full Project

Welcome folks today in this blog post i will be talking about how to compress and extract files into a zip file using python built in library called as zipfile. Let’s get started. You can see the step by step youtube video as follows:

 

Compressing Single File

 

READ  FFMPEG Command to Extract Frames From Video With Timestamp or Convert Video to Images Full Tutorial For Beginners

In this block of code we will see how to compress a single file using zipfile module in python.

 

import zipfile
         
jungle_zip = zipfile.ZipFile('C:\\Stories\\Fantasy\\jungle.zip', 'w')
jungle_zip.write('C:\\Stories\\Fantasy\\jungle.pdf', compress_type=zipfile.ZIP_DEFLATED)
 
jungle_zip.close()

 

 

Compressing Multiple Files

 

import os
import zipfile
 
fantasy_zip = zipfile.ZipFile('C:\\Stories\\Fantasy\\archive.zip', 'w')
 
for folder, subfolders, files in os.walk('C:\\Stories\\Fantasy'):
 
    for file in files:
        if file.endswith('.pdf'):
            fantasy_zip.write(os.path.join(folder, file), os.path.relpath(os.path.join(folder,file), 'C:\\Stories\\Fantasy'), compress_type = zipfile.ZIP_DEFLATED)
 
fantasy_zip.close()

 

READ  FFMPEG Command to Create Video From Single Image By Looping For Specific Duration Full Tutorial For Beginners

So now in this block of code we are compressing a whole directory of pdf files into a single zip file.

 

 

import zipfile
         
fantasy_zip = zipfile.ZipFile('C:\\Stories\\Fantasy\\archive.zip')
fantasy_zip.extractall('C:\\Library\\Stories\\Fantasy')
 
fantasy_zip.close()

 

Leave a Reply