zip a file python code example

Example 1: python zip function

>>> numbers = [1, 2, 3]
>>> letters = ['a', 'b', 'c']
>>> zipped = zip(numbers, letters)
>>> zipped  # Holds an iterator object
<zip object at 0x7fa4831153c8>
>>> type(zipped)
<class 'zip'>
>>> list(zipped)
[(1, 'a'), (2, 'b'), (3, 'c')]  #list of tuples  
# zip returns tuples

Example 2: zip python

>>> x = [1, 2, 3]
>>> y = [4, 5, 6]
>>> for t in zip(x, y):
...   print(t)
...
(1, 4)
(2, 5)
(3, 6)

Example 3: zip python

number_list = [1, 2, 3]
str_list = ['one', 'two', 'three']

# No iterables are passed
result = zip()

# Converting itertor to list
result_list = list(result)
print(result_list)

# Two iterables are passed
result = zip(number_list, str_list)

# Converting itertor to set
result_set = set(result)
print(result_set)

>>>[]
{(2, 'two'), (3, 'three'), (1, 'one')}

Example 4: 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)

Example 5: zip python

>>> x = [1, 2, 3]
>>> y = [4, 5, 6]
>>> zipped = zip(x, y)
>>> list(zipped)
[(1, 4), (2, 5), (3, 6)]
>>> x2, y2 = zip(*zip(x, y))
>>> x == list(x2) and y == list(y2)
True