使用Python从ArcMap删除图层


9

问题:

  • 我正在尝试遍历所有图层,以查找名为的图层"CADAnnotation"
  • 如果该层存在,则从mxd中删除该层

笔记:

  • 从独立脚本运行(即不在Arcmap中)
  • "CADAnnotation" 数据类型是CAD注释要素类
  • "CADAnnotation" 不是在地理数据库中,而是从AutoCAD .dwg创建的
  • "CADAnnotation" 在名为 "ACAD"
  • 如果"ACAD"可以删除组图层,那也可以删除它"CADAnnotation"

到目前为止的代码:

for item in mxds:
    print (item)
    mxd = arcpy.mapping.MapDocument(item)
    df=arcpy.mapping.ListDataFrames(mxd,"Project Area")[0]
    for lyr in arcpy.mapping.ListLayers(mxd, "*",df):
        if lyr.name == "CADAnnotation":
            print(lyr.dataSource)
            arcpy.Delete_management("CADAnnotation")
            print("Layer Deleted")
        else:
            pass

代码注释:

  • 我可以找到图层没问题
  • 该行arcpy.Delete_management("CADAnnotation")不起作用会引发错误。

题:

  • 如何删除"CADAnnotation"和/或"ACAD"分组图层?

Answers:


17

您是要从地理数据库中实际删除图层还是要从mxd中删除图层?

如果您只想从mxd中删除图层,请替换arcpy.Delete_management("CADAnnotation")arcpy.mapping.RemoveLayer(df, lyr)

如果要删除数据源,可以执行此操作。

for item in mxds:
   print (item)
   mxd = arcpy.mapping.MapDocument(item)
   df=arcpy.mapping.ListDataFrames(mxd,"Project Area")[0]
   for lyr in arcpy.mapping.ListLayers(mxd, "*",df):
      if lyr.name == "CADAnnotation":
         arcpy.mapping.RemoveLayer(df, lyr)
         print(lyr.dataSource)
         arcpy.Delete_management(lyr.dataSource)
         print("Layer Deleted")
      else:
         pass
By using our site, you acknowledge that you have read and understand our Cookie Policy and Privacy Policy.
Licensed under cc by-sa 3.0 with attribution required.