python zipfile 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: make zipfile from directory py

import zipfile
filePaths = [] # Make an array string with all paths to files
for root, directories, files in os.walk("MyDirectoryPath"): # Scans for all subfolders and files in MyDirectoryPath
        for filename in files: # loops for every file
            filePath = os.path.join(root, filename) # Joins both the directory and the file name
            filePaths.append(filePath) # appends to the array
z = zipfile.ZipFile("MyDirectoryPathWithZipExt.zip", 'w')
with z:
    for file in filePaths: # Loops for all files in array
        z.write(file) # Writes file to MyDirectoryPathWithZipExt.zip

Example 3: python zip function

>>> letters = ['a', 'b', 'c']
>>> numbers = [0, 1, 2]
>>> for l, n in zip(letters, numbers):
...     print(f'Letter: {l}')
...     print(f'Number: {n}')
...
Letter: a
Number: 0
Letter: b
Number: 1
Letter: c
Number: 2