Hi i need to automatize workflow using python. I have to open a dxf file, and change one text inside it and the name of a shape. I am using ezdxf module. I can see the layers but when i try to change the name of one of them and save the file create a new layer with the new name. Thanks in advance.
dwg = ezdxf.readfile('path_to_my_file.dxf')
for layer in dwg.layers:
if layer.dxf.name == 'old_layer_name':
layer.dxf.name = 'new_layer_name'
The DXF format is very loose and layer names are specified both in the LAYERS
table as well as on every item in the ENTITIES
table (and also potentially in some OBJECTS
, too), so you'll have to update layer names everywhere for it to take effect.
I don't know anything about the ezdxf
library but what likely is happening is that when saving the file, the library notices that even you renamed 'old_layer_name'
to 'new_layer_name'
, there are still entities that specify 'old_layer_name'
so the library adds that layer to the LAYERS
table to try to maintain consistency.
The end result will look something like this ( untested ):
# your existing code
dwg = ezdxf.readfile('path_to_my_file.dxf')
for layer in dwg.layers:
if layer.dxf.name == 'old_layer_name':
layer.dxf.name == 'new_layer_name'
# this is the part that's untested
for entity in dwg.entities:
if entity.layer.dxf.name == 'old_layer_name':
entity.layer.dxf.name == 'new_layer_name'
If you just rename the layer in the layers table, does not change the layer of any entity, because all entities have it's own layer attribute, which determines on which layer an entity appears. This has to be done manually for all layout spaces including the model space and also in all block definitions.
Example just for the model space:
import ezdxf
dwg = ezdxf.readfile('old.dxf')
msp = dwg.modelspace()
OLD_LAYER_NAME = 'old_layer_name'
NEW_LAYER_NAME = 'new_layer_name'
# rename layer
try:
layer = dwg.layers.get(OLD_LAYER_NAME)
except ValueError:
print('Layer {} not found.'.format(OLD_LAYER_NAME))
else:
layer.dxf.name = NEW_LAYER_NAME
# move entities in model space to new layer
all_entities_on_old_layer = dwg.modelspace().query('*[layer=="%s"]' % OLD_LAYER_NAME)
for entity in all_entities_on_old_layer:
entity.dxf.layer = NEW_LAYER_NAME # this assigns the new layer
dwg.saveas('new.dxf')
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.