Is there no way to delete an empty layer from the layer list? I want to do the same thing as the autocad purge command.
I tried to write the code but it didn't work.
del_lay = []
for layer in dwg.layers:
s = layer.dxf.name
lay_= re.search(layer.dxf.name, s)
if lay_:
L = lay_.group()
del_lay.append(L)
del_lay.remove("0") #0 layer cannot be deleted, so remove it from the list
for Lay in del_lay:
all_entities = dwg.modelspace().query('*[layer=="%s"]' % Lay)
print(all_entities)
for entity in all_entities: #If there is no entity in the layer
if entity not in all_entities:
delete_name = layer.dxf.name
my_lines = dwg.layers.get(delete_name)
dwg.layers.remove(my_lines)
When I check it myself, there is a layer where entity does not exist, but it is not executed.
NameError: name 'delete_name' is not defined
Firstly, consider that the following if
statement will never be validated:
for entity in all_entities: #If there is no entity in the layer
if entity not in all_entities:
Within the for
loop you are iterating over the contents of all_entities
, hence your test expression: entity not in all_entities
will never return True since by the very definition of the for
loop, entity
must be a member of all_entities
.
In response to your main question: before removing a layer definition from a DXF file, you will need to ensure that the layer name has no references anywhere in the database.
This therefore necessitates iterating over all entities in the entire drawing database (i.e. primary entities in all drawing layouts, subentities (e.g. ATTRIB
, VERTEX
, SEQEND
entities), entities within all block definitions, and also the block definition bookends (BLOCK
, ENDBLK
).