我有一个ArcMap文件(.MXD),我想搜索它的图层,然后选择一个图层,让Python显示该图层属性表的字段名称。
到目前为止,Python(ArcPy)列出了mxd的图层名称,但我无法弄清楚如何获取字段名称。
在ArcMap本身,我可以这样轻松地做到这一点:
fields = arcpy.ListFields(Layer)
for field in fields:
print field.name
但是如何通过MXD文件在ArcMap之外完成?我经常搜索并没有提出任何建议,所以我期待着你的帮助!非常感谢!
答案 0 :(得分:1)
通过arcpy.mapping.MapDocument
方法访问mxd。然后获取名称并打开属性表
mxd = arcpy.mapping.MapDocument(r"path/Project.mxd")
for df in arcpy.mapping.ListLayers(mxd):
print df.name
您可以使用arcpy
并运行python脚本以使用ListFileds
方法显示表格文件
import arcpy
fieldList = arcpy.ListFields("path/shapefile.shp")
for field in fieldList:
print field.baseName
答案 1 :(得分:0)
好的,我找到了一个很好的解决方案。我首先从MXD文件中获取所有图层,然后将每个图层的名称和源保存到字典中。然后我将从GUI中选择我想要的图层并使用字典中的图层名称进行检查,然后我可以通过该名称访问字段名称:
import arcpy
mxd = arcpy.mapping.MapDocument(r"C:\MyMap.mxd") # loads my map
df = arcpy.mapping.ListDataFrames(mxd) # checks out the dataframes
layersources = {} # creates an empty dictionary
for d in df:
layers = arcpy.mapping.ListLayers(mxd, "", d) # lists all available layers
for lyr in layers:
layersources[lyr.name] = lyr.dataSource # fills keys and values of the layers (names and sources) into the dictionary
selecteditem = "the wanted layer" # this I choose from a GUI then, just defined it here as a variable for testing purposes
fields = arcpy.ListFields(layersources[selecteditem]) # creates a list with all the fields from that layer
for field in fields: # iterates through the list of fields
print field.name # and prints them one by one :-)