Assign objects to AutoCAD layers in Python

Python can be used for layer creation in AutoCAD. I have documented this in a separate article here on SCDA. In this article I document how objects can be assigned to AutoCAD layers using Python.

# import win32com
import win32com.client

# access currently active AutoCAD drawing
acad = win32com.client.Dispatch("AutoCAD.Application")
doc = acad.ActiveDocument

# access Layers collection of currently active document
layers = doc.Layers

# add new layer to existing collection (named newlayer)
new_layer = layers.Add("newlayer")

# draw a line in model space
line = acad.ActiveDocument.ModelSpace.AddLine((0, 0), (10, 10))

# adjust .Layer property of line and thereby assign it to desired layer (.Name)
line.Layer = new_layer.Name

In above Python code I import win32com, access the currently open drawing and add a new layer. I draw a line and assign the new layer to the layer property of the newly drawn line. Thereby, I assigned the new line object to the desired AutoCAD layer.