Load a Folder of DWGs and Run A Python Script on Each File

With Dynamo Nodes that we have available today, is there a way to run a python node on several DWGs located in the same folder? I see there was a post about this several years ago, and I was wondering if any developments have been made since then? I am happy to share the python script that I would like to run if needed. Thanks!

I don’t know enough to conduct the process through side databases but you can put the python code into this loop to open the dwgs and run the code on each one. (Make sure you are using ironpython)

Just pass in a list of DWG paths. Example → [“F:\Projects\1750\site.dwg”, “F:\Projects\1750\base.dwg”]

You can collect the dwg paths in a directory with the os module: Python - List Files in a Directory - GeeksforGeeks
You can also use python to filter out files that aren’t “.dwgs”.
I think this thread has a ton of really good information regarding iterating through dwgs with python: Rename XREFs in multiple dwgs - #50 by WrightEngineering
If you download that .dyn it should have plenty of code in there that you can take and use.

@jacob.small also has a really good zoom recording further up on that thread that provides a good example of the process of creating a python script to iterate through multiple dwgs.

for DWGPath in DWGPaths:
    adoc = DocumentCollectionExtension.Open(acapp.DocumentManager, DWGPath, False)


    with adoc.LockDocument():
        with adoc.Database as db:
            with db.TransactionManager.StartTransaction() as t:
                #INSERT CODE HERE

                t.Commit()
                pass
                
    if adoc:
        DocumentExtension.CloseAndSave(adoc, DWGPath)
3 Likes

In addition to this, if a node exists that does the things you need to a single DWG, you can make it work across multiple by setting the filepath to @L1 and longest lacing.

It has been possible to do this sort of thing for a long time now, but with the requirement of Python knowledge and adding loops to these like @WrightEngineering mentions in their great overview.

1 Like

This is great stuff, and the videos you mentioned are also great thank you for sharing. I was able to get two python scripts set up (one will open up files in a given directory, and then save and close. The second script accesses the open drawings Layout tab viewport and sets the view from a set of given parameters. Both scripts are pretty simple in nature.

I am having problems when I try to merge the two scripts together to form a complete code that will open up each file in a given directory, set the view, save&close, and move on to the next file and do the same. Most of the problems are probably set up related. If anyone has a few minutes to take a look that would be great. I have attached two sample DWGs and the .DYN

How do you insert the code into your response as you did above? I can add where I am currently at with my script.

101.dwg (487.4 KB)
102.dwg (523.2 KB)
BVSPC_ImportGridInformation_Mult.dyn (48.1 KB)


Click the preformatted text button or ctrl + e :slight_smile:

This is where the code currently site. I probably have some syntax errors.

# Load the Python Standard and DesignScript Libraries
import clr
import os

# Add Assemblies for AutoCAD and Civil3D
clr.AddReference('AcMgd')
clr.AddReference('AcCoreMgd')
clr.AddReference('AcDbMgd')
clr.AddReference('AecBaseMgd')
clr.AddReference('AecPropDataMgd')
clr.AddReference('AeccDbMgd')

import Autodesk.AutoCAD.ApplicationServices.Application as acapp

# Import references from AutoCAD
from Autodesk.AutoCAD.Runtime import *
from Autodesk.AutoCAD.ApplicationServices import *
from Autodesk.AutoCAD.EditorInput import *
from Autodesk.AutoCAD.DatabaseServices import *
from Autodesk.AutoCAD.Geometry import *

import Autodesk.AutoCAD.ApplicationServices.DocumentCollectionExtension

# Import references from Civil3D
from Autodesk.Civil.ApplicationServices import *
from Autodesk.Civil.DatabaseServices import *

#Data Entering Python Node
objects = IN[0]
name = IN[1]
vh  = IN[2]
vw  = IN[3]
rotation = IN[4]
directory = IN[5]

#get list of files in folder path
fileList = os.listdir(directory)
#remove any files that do not have extension .dwg
fileList2 = [f for f in fileList if ".dwg" in f]
#create list of file paths
pathList = [directory+"\\"+f for f in fileList if ".dwg" in f ]

#Function is designed to 1. Open up the first .dwg file in the directory 2. Navigate to the Layout1 tab 3. Get the viewport information and set the view to the given coordinates 4. Lock viewport 5. Save and Close 6. Repeat for each file in the directory

def viewport_zoom(objects, name, vh, vw, rotation, directory):
    for path in pathList:
        adoc = DocumentCollectionExtension.Open(acapp.DocumentManager, path, False)
        acapp.DocumentManager.CurrentDocument = adoc
        try:
            with adoc.LockDocument():
                with adoc.Database as db:
                    with db.TransactionManager.StartTransaction() as t:
                        # Code between here
                        bt = t.GetObject(db.BlockTableId, OpenMode.ForWrite)
                        btr = t.GetObject(bt[BlockTableRecord.ModelSpace], OpenMode.ForWrite)
                        ii = 0
                        for i in name:
                            lm = LayoutManager.Current.CurrentLayout = name[ii]
                            lmm = LayoutManager.Current
                            objly = t.GetObject(lmm.GetLayoutId(lmm.CurrentLayout), OpenMode.ForWrite)
                            vids = objly.GetViewports()
                            vport = t.GetObject(vids[0], OpenMode.ForWrite)
                            vport.Locked = False
                            ed.SwitchToModelSpace()
                            view = ViewTableRecord()
                            view.CenterPoint = Point2d(objects[ii].X, objects[ii].Y)
                            # viewtwist should be positive for clockwise rotation
                            view.ViewTwist = rotation
                            view.Height = vh
                            view.Width = vw
                            ed.SetCurrentView(view)
                            vport.Locked = True
                            ed.SwitchToPaperSpace()
                            vport.Locked = True
                            res.append(view)
                            ii += 1
                        # Code between here
                        t.Commit()               
                
    	if adoc:
        	DocumentExtension.CloseAndSave(adoc, path)

# Assign your output to the OUT variable.
OUT = viewport_zoom(objects,name,vh,vw,rotation,directory):

Is anyone on the forum able to take a look and review this code? The graph is still in development as I am stumped on how to get the combined code to function properly. thanks