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
import os
import zipfile
def zipdir(path, ziph):
# ziph is zipfile handle
for root, dirs, files in os.walk(path):
for file in files:
ziph.write(os.path.join(root, file),
os.path.relpath(os.path.join(root, file),
os.path.join(path, '..')))
zipf = zipfile.ZipFile('Python.zip', 'w', zipfile.ZIP_DEFLATED)
zipdir('tmp/', zipf)
zipf.close()