I want to know how to use ezdxf to add sequential numbers to layer names.
AutoCAD layer name list:
Layer name list after change:
I want to change the layer name as above.
I tried using a for
statement, but it doesn't work.
import ezdxf
import glob
from pathlib import Path
import os
import re
from typing import TYPE_CHECKING, TextIO, Iterable
file_list=glob.glob('./input/*.dxf')
for filename in file_list:
dwg = ezdxf.readfile(filename,encoding='auto',legacy_mode=False)
msp = dwg.modelspace()
old_layername1 = '\w+'
for layer in dwg.layers:
s=layer.dxf.name
old_layername11 = re.search(old_layername1,s)
if old_layername11:
old_layername11=old_layername11.group()
for i in range(1,10):
new_layername1 = 'AAA'+str(i)
try:
layer = dwg.layers.get(old_layername11)
except ValueError:
print('Layer {} not found.'.format(old_layername11))
else:
layer.dxf.name = new_layername1
The numbers after all layer names become the same number.
You don't need a separate for
loop to increment the variable i
; instead, increment this variable as you iterate over the layer collection.
i.e.:
i = 1
for layer in dwg.layers:
new_layername1 = 'AAA' + str(i)
...
i += 1
You may also want to check whether the target layer name exists prior to renaming.