-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathcreate_zip_and_unzip.py
83 lines (68 loc) · 2.82 KB
/
create_zip_and_unzip.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
#-------------------------------------------------------------------------------
# Name: create_zip.py
# Purpose: This Python script takes an input folder and creates a zip file and stores in the output folder.
# Author: Kiran Chandrashekhar
# Created: 18-Dec-2022
#-------------------------------------------------------------------------------
import os
from random import randint
import zipfile
import shutil
class CreateZip:
def __init__(self):
pass
def get_all_files(self, directory:str)->list:
"""
Get all the files from the directory
"""
complete_file_list = []
for dirname, subdirs, files in os.walk(directory):
file_list = [os.path.join(dirname, file) for file in files]
complete_file_list.extend(file_list)
return complete_file_list
#-------------------------------------------------#
# Create Zip File from the folder - v1 #
#-------------------------------------------------#
def create_zip_file(self, directory:str)->str:
"""
Create a zip file from the list of all the file from the
specified directory
"""
file_list = self.get_all_files(directory)
zip_file = f"{os.getcwd()}/output/{randint(100_000,999_999)}.zip"
with zipfile.ZipFile(zip_file, "w") as zf:
for file in file_list:
relative_path = os.path.relpath(file, directory)
zf.write(file, relative_path)
return zip_file
#-------------------------------------------------#
# Create Zip File from the folder - v2 #
#-------------------------------------------------#
def create_zip_file_v2(self, directory:str)->str:
"""
Create a zip file from the list of all the file from the
specified directory
"""
zip_file = f"{os.getcwd()}/output/{randint(100_000,999_999)}"
zip_path = shutil.make_archive(zip_file, 'zip', directory)
return zip_path
#-------------------------------------------------#
# Unzip the file #
#-------------------------------------------------#
def unzip_file(self, zip_file:str)->str:
"""
Unzip the file and save the extracted files in the output folders
"""
output_folder = f"{os.getcwd()}/output/{randint(100_000,999_999)}"
with zipfile.ZipFile(zip_file, 'r') as zip_ref:
zip_ref.extractall(output_folder)
return output_folder
def main():
obj = CreateZip()
directory = f"{os.getcwd()}/input/"
zip_file_path = obj.create_zip_file(directory)
output_folder = obj.unzip_file(zip_file_path)
print(output_folder)
if __name__ == '__main__':
main()
print("Done")