create zip file python3 code example
Example 1: python zip folder
import os
import zipfile
def zip_directory(folder_path, zip_path):
with zipfile.ZipFile(zip_path, mode='w') as zipf:
len_dir_path = len(folder_path)
for root, _, files in os.walk(folder_path):
for file in files:
file_path = os.path.join(root, file)
zipf.write(file_path, file_path[len_dir_path:])
zip_directory('C:/FolderToZip', 'C:/Folder.zip')
Example 2: extracting zip files python
import os
import optparse
import zipfile
def get_arguments():
parser = optparse.OptionParser()
parser.add_option("--src","--source",dest="paths", help="Removing file with extension .SRT and .VTT")
(options,arguments)=parser.parse_args()
if not options.paths:
parser.error("[-] Please specify source, use --help for more info.")
return options
def Source_folder(folder_path):
print('[+] Extracting zip file')
for path, dir_list, file_list in os.walk(folder_path):
try:
for file_name in file_list:
if file_name.endswith(".zip"):
abs_file_path = os.path.join(path, file_name)
parent_path = os.path.split(abs_file_path)[0]
output_folder_name = os.path.splitext(abs_file_path)[0]
output_path = os.path.join(parent_path, output_folder_name)
zip_obj = zipfile.ZipFile(abs_file_path, 'r')
zip_obj.extractall(output_path)
zip_obj.close()
except FileNotFoundError:
print('Error', file_name)
options = get_arguments()
Source_folder(options.paths)