Creating a new layer using Python script

Hi all,

I have a question about the creating a new layer using Python script.

I want to create 10 layers and naming 01 to 10 separately as below shown
image

I also tried to adapt the Python script from Dale’s script.
Link:Creating a new layer and renaming automatically using Python script - #3 by dale


Thank you so much

Dale’s script is robust, and intentionally avoids name clashes with pre-existing layers.

If you know (and can own) that there are no existing layers already with the names desired for the new ones (“01”,…,“10”) then it’s just a matter of:

sc.doc = Rhino.RhinoDoc.ActiveDoc

red = System.Drawing.Color.Red
for i in range(1,11):
    sc.doc.Layers.Add(str(i).zfill(2), red)

sc.doc = ghdoc

But the second time this script is run, it will clash with the layers created by the first run. Double check .Layers.Add does what you want in this situation.

And if you are running just Python scripts directly in Rhino and not via Grasshopper then it looks like this:

Simple, starting at 1 and going to n layers (user input):

import rhinoscriptsyntax as rs

def AddNumberedLayers():
    count=rs.GetInteger("Number of layers to add",minimum=1)
    if count is None: return
    
    for i in range(1,count+1):
        layername="{}".format(i).zfill(3)
        if not rs.IsLayer(layername): rs.AddLayer(layername)
AddNumberedLayers()

Allowing choice of start number and end number:

import rhinoscriptsyntax as rs

def AddNumberedLayersStartFin():
    start_n=rs.GetInteger("Number to start with",minimum=0)
    if start_n is None: return
    end_n=rs.GetInteger("Number to end with",minimum=start_n+1)
    if end_n is None: return
    
    for i in range(start_n,end_n):
        layername="{}".format(i).zfill(3)
        if not rs.IsLayer(layername): rs.AddLayer(layername)
AddNumberedLayersStartFin()

These will not attempt to add an already existing same-numbered layer.

Note the layer color is determined by the default layer color set in Rhino. One can also give them all a specific color, or a random color or…

For a specific color one can simply replace the line

if not rs.IsLayer(layername): rs.AddLayer(layername)

with

if not rs.IsLayer(layername): rs.AddLayer(layername,rs.coercecolor([255,0,0]))

where the number in the square brackets represents the RGB color.

The number of leading zeroes can be controlled by changing the number in the parentheses .zfill(3)

1 Like

Hi James,
Thank you for your help

Hi Helvetosaur,
You’ve saved my life. You’ve been a lifesaver.