2016-11-16 92 views
0

我有一個ArcMap文件(.MXD),我想要搜索其圖層,然後選擇一個圖層並讓Python向我顯示該圖層的屬性表的字段名稱。列出MXD文件中圖層的字段名稱

我已經到目前爲止,Python(ArcPy)列出了mxd的圖層名稱,但我無法弄清楚如何獲取字段名稱。

在ArcMap本身,我可以很容易地做到這一點是這樣的:

fields = arcpy.ListFields(Layer) 
for field in fields: 
    print field.name 

,但我怎麼做到ArcMap中的那個外面通過MXD文件?我搜查了很多東西,結果什麼也沒有,所以我期待着你的幫助!非常感謝!

回答

1

通過arcpy.mapping.MapDocument方法訪問mxd。然後得到的名稱和使用方法ListFileds

import arcpy 
fieldList = arcpy.ListFields("path/shapefile.shp")  
for field in fieldList:  
    print field.baseName 
+0

是的,對於shapefile很明顯。重點是使用MXD並從那裏指向圖層。像'arcpy.ListFields(mxd,Layer)',但這不起作用。任何想法? – Khaled

+0

@Khaled ok我添加了選項來迭代mxd –

+0

中的形狀文件,然後其他解決方案只給出MXD的圖層。我想Python打開MXD,給我一個我選擇的圖層列表(GUI),然後獲取該圖層的字段。但我找到了一個解決方案(見下文)。必須欺騙一些。任何人有更好的解決方案,歡迎發佈! – Khaled

0

好,我找到了一個很好的解決方案打開屬性表

mxd = arcpy.mapping.MapDocument(r"path/Project.mxd") 
for df in arcpy.mapping.ListLayers(mxd): 
    print df.name 

您可以使用arcpy並運行一個python腳本,以顯示該表的Fileds。我首先從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 :-)