Zipping and Unzipping files in Python














































Zipping and Unzipping files in Python



Description:

ZIP is an archive file format that supports lossless data compression. By lossless compression, it means that the 

compression algorithm used allows the original data to be perfectly reconstructed from the compressed data.

Also, a ZIP file may contain one or more files or directories that may have been compressed.



Sample Output:

Enter name of directory to be zipped: SampleDirectory

The following files will be zipped:

SampleDirectory/SampleFile1.txt

SampleDirectory/SampleFile2.txt


Zipping successful!

The files are zipped into zipped.zip file.



Enter name of directory to be unzipped: zipped.zip

Unzipping successful!




Implementation:

import os
from zipfile import ZipFile

#class for compressing files
class Zipper:
def __init__(self):
self.filePaths = list()


#method to zip/compress files
def zip(self):
#directory = input("Enter name of directory to be zipped: ")
directory =
"SampleDirectory"
self.getAllFilePaths(directory)

print(
"The following files will be zipped:")
#to print all the files that are to be zipped
for file in self.filePaths:
print(file)

#zipping files
with ZipFile("zipped.zip", "w") as zip:
for file in self.filePaths:
zip.write(file)

print(
"\nZipping successful!\nThe files are zipped into zipped.zip file.\n")


#method to get the file paths for all files to be zipped
def getAllFilePaths(self, directory):
#os.walk function can be used to perform a directory walk
#and get all the files present in it
for root, directories, files in os.walk(directory):
for fileName in files:
filepath = os.path.join(root, fileName)
self.filePaths.append(filepath)


#class for decompressing files
class Unzipper:
#method to unzip/decompress files
def unzip(self):
#directory = input("Enter name of directory to be unzipped: ")
directory =
"zipped.zip"

#check if the file name is valid and unzip
try:
zip = ZipFile(directory,
"r")

# print("The following files will be unzipped in the currently working directory:")
# zip.printdir()
zip.extractall()
print(
"Unzipping successful!")
except:
print(
"File not found!")


def main():
newZip = Zipper()
newZip.zip()

newUnzip = Unzipper()
newUnzip.unzip()


if __name__ == "__main__":
main()


Comments