python zip files 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: 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 3: 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

Example 4: 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 5: 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 6: 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')}