Node / Python to create zip of directory contents?

Does anyone know of a node (or python way) to create zip files using dynamo?

Ideally it would be able to:

  1. input a list of files or directories
  2. input the name of the zip
  3. input the location to save the resulting zip

I am not aware of a node to do this, but it certainly looks doable - the documentation on the zipfile module can be found here: zipfile — Work with ZIP archives — Python 3.8.16 documentation

(if you are using the older Python 2 format you may need to select that documentation version from the dropdown).

Give it a shot and see where you get with it. :slight_smile:

1 Like

Hello @Bren - you can use the Shutil module for simple operations (i.e. Zipping an entire folder!)

image

import shutil #Import the Shutil module that offers high-level operations on files and collections of files

#Inputs
zipDirectory = IN[0] #Define the directory of files we want to Zip up
zipLocation = IN[1] #Define the location we want our Zip file to be created at
name = IN[2] #Define the name of our zip file
format = IN[3] #Define the format we want to use - either Zip or Tar

_zippedFile = shutil.make_archive(name, format, zipDirectory) # We use the Shutil module to make an archive

_move = shutil.move(_zippedFile, zipLocation) #Then we move that module to the correct location as, by default, it will be created in the Dynamo install location

OUT = _move #We then output the final result to see a success message!
7 Likes

I’m getting the error No module named shutil because I’m using Revit 2019 and Dynamo 2.0.3.8811.

snip_20211021085302

To fix it, I tried installing python via their main installer package but dynamo still doesn’t know about shutil.

Is it possible in older versions of dynamo?

zip.dyn (7.4 KB)

2 examples with folder compression

with zipfile python module

import sys
import clr
import System

pf_path = System.Environment.GetFolderPath(System.Environment.SpecialFolder.ProgramFilesX86)
sys.path.append(pf_path + '\\IronPython 2.7\\Lib')
import os
import zipfile

folderPath = IN[0]
zipName = IN[1]
zipPath = os.path.abspath(os.path.join(os.path.dirname(folderPath), zipName))

with zipfile.ZipFile(zipPath, "w") as zip:
	for root, dir, files in os.walk(folderPath):
		for file in files:
			if file not in zipPath:
				zip.write(root + "\\" + file, file)
				
OUT = zipPath

with Python Engines work on Net FrameWork 4.5 or above

import sys
import clr
import System
from System.IO.Compression import ZipFile, CompressionLevel
from System.IO import Directory, Path, File

folderPath = IN[0]
zipName = IN[1]
dirInfo = Directory.GetParent(folderPath)
zipPath = Path.Combine(Directory.GetParent(folderPath).FullName, zipName)
if  File.Exists(zipPath):
    File.Delete(zipPath)
ZipFile.CreateFromDirectory(folderPath, zipPath)
OUT = zipPath
4 Likes

Working well now. Thanks for all the help!

1 Like