Creating and Extracting Zip Files using Python
Avinash Reddy P.
Avinash Reddy P.
Senior Data Engineer | Microsoft Certified: Azure Data Engineer Associate | Master's degree in Computer Science
import zipfile import shutil import requests #Create Zip File by appending the files #and compress the file to reduce it's size #
def createZipFileFromFiles(): with zipfile.ZipFile('files.zip', 'w', compression=zipfile.ZIP_DEFLATED) as my_zip: my_zip.write('NEWS.txt') my_zip.write('LICENSE.txt') #Extract Files from the Zip File #either all into one folder #or only required ones # def extractFilesFromZipFile(): with zipfile.ZipFile('files.zip', 'r') as my_zip: #extracts all files in zip folder my_zip.extractall('files') #extract particular named file in zip folder my_zip.extract('LICENSE.txt', 'files1/') # #Make a normal folder as Zip Folder using shutil # def makeFolderAsZip(): shutil.make_archive('another', 'zip', 'Scripts') # #Extract the Zip Folder into Normal Folder # def extractZipFolder(): shutil.unpack_archive('another.zip', 'another') # #Download Content into Zip File using the URL # def downloadContentToZipFromURL(r): with open('data.zip', 'wb') as f: f.write(r.content) # #View the list of files in the Zip folder # def viewContentsOfZip(con): with zipfile.ZipFile(con, 'r') as data_zip: print(data_zip.namelist()) #Web URL r = requests.get( 'https://github.com/MarczakIO/azure4everyone-samples/archive/master.zip') createZipFileFromFiles() extractFilesFromZipFile() makeFolderAsZip() extractZipFolder() downloadContentToZipFromURL(r) viewContentsOfZip('files.zip') viewContentsOfZip('data.zip') viewContentsOfZip('another.zip')
With the help of functions, we can make code reusable for any number of times. We can also implement this logic in extracting the live generated files and loading them into the server. We can get the hyperlinks or filenames of live generated files by using the beautiful soup libraries in python.