首页 > 解决方案 > 从 .dxf 文件中获取图层并将该图层复制到新文件

问题描述

我已经尝试了可以​​在此处找到的以下代码,我的目标是从 .dxf 文件中取出一层,然后仅使用该信息将其复制到新文件中。在我找到代码的链接上,制作了以下代码,但我不明白为什么我有错误。我尝试更改图层名称,但没有成功。

from shutil import copyfile
import ezdxf

ORIGINAL_FILE = 'test.dxf'
FILE_COPY = 'test2.dxf'

KEEP_LAYERS = {'Layer1', 'Layer2', 'AndSoOn...'}
KEEP_LAYERS_LOWER = {layer.lower() for layer in KEEP_LAYERS}

# copy original DXF file
copyfile(ORIGINAL_FILE, FILE_COPY)

dwg = ezdxf.readfile(FILE_COPY)
msp = dwg.modelspace()
# AutoCAD treats layer names case insensitive: 'Test' == 'TEST'
# but this is maybe not true for all CAD applications.
# And NEVER delete entities from a collection while iterating.
delete_entities = [entity for entity in msp if entity.dxf.layer.lower() not in KEEP_LAYERS_LOWER]

for entity in delete_entities:
    msp.unlink_entity(entity)
   
dwg.save()

我的案例非常简单,与该代码类似,但出现以下错误:

    raise const.DXFAttributeError(

DXFAttributeError: Invalid DXF attribute "layer" for entity MPOLYGON

我没有找到与该错误相关的任何参考书目,网站上没有太多关于此库错误的信息。

标签: pythonlayerdxfezdxf

解决方案


MPOLYGON 未记录在 DXF 参考中,因此仅保留为 DXFTagStorage 并且没有图层属性。

没有图层属性的实体将被删除:

delete_entities = [
     e for e in msp 
     if not e.dxf.is_supported('layer') or e.dxf.layer.lower() not in KEEP_LAYERS_LOWER
]

编辑:不支持的实体的取消链接将在 v0.16.2 中工作,直到销毁实体:

for e in msp:
    if e.dxf.is_supported('layer') and e.dxf.layer.lower() in KEEP_LAYERS_LOWER:
        continue
    e.destroy()

  

也许您可以发布您的 DXF 文件(压缩)以查看 MPOLYGON 应该是什么,我猜它是已经支持的 DXF 类型的同义词。

编辑:MPOLYGON 似乎是 AutoCAD Map 特定实体。


推荐阅读