2017-04-18 38 views
1

我想問一些關於使用ArcPy處理ArcGIS地圖文檔(MXD)中的特徵數據的腳本。使用ArcPy將所有文件特徵數據(shapefile)從文件夾添加到MXD中

我有一個在shapefile(shp)窗體中具有一些功能數據的文件夾。

  • d:\ TES \ 2240.shp
  • d:\ TES \ 2250.shp
  • d:\ TES \ 22460.shp

我想創建一個可將上述數據添加到MXD的ArcPy腳本。

import arcpy 
mxd = arcpy.mapping.MapDocument(r"D:\tes\Operation.mxd") 
df = arcpy.mapping.ListDataFrames(mxd, "Layers")[0] 
targetGroupLayer = arcpy.mapping.ListLayers(mxd, "Actual", df)[0] 
addLayer = arcpy.mapping.Layer(r"D:\data\2440.shp") 
arcpy.mapping.AddLayerToGroup(df, targetGroupLayer, addLayer, "TOP") 
addLayer = arcpy.mapping.Layer(r"D:\data\2450.shp") 
arcpy.mapping.AddLayerToGroup(df, targetGroupLayer, addLayer, "TOP") 
addLayer = arcpy.mapping.Layer(r"D:\data\2460.shp") 
arcpy.mapping.AddLayerToGroup(df, targetGroupLayer, addLayer, "TOP") 
mxd.saveACopy(r"D:\tes\Operation_2.mxd") 
del mxd, addLayer 

我想改變腳本的路徑源數據上面,在這部分

addLayer = arcpy.mapping.Layer(r"D:\data\2440.shp") 

因此腳本可以在文件夾中添加所有SHP數據:我可以單獨使用這個腳本添加文件使用擴展名,而不是每個文件名硬編碼。有點像這樣:

addLayer = arcpy.mapping.Layer(r"D:\data\*.shp") 

什麼是正確的方法來做到這一點?

+0

您需要包含顯示您嘗試過的代碼。謝謝! –

回答

1

Create a list of all the shapefiles in the directory,然後遍歷它。

import arcpy 
mxd = arcpy.mapping.MapDocument(r"D:\tes\Operation.mxd") 
df = arcpy.mapping.ListDataFrames(mxd, "Layers")[0] 

# set workspace to directory of interest 
arcpy.env.workspace = r"D:\data" 
# create list of all files ending in .shp 
list_shapefiles = arcpy.ListFiles("*.shp") 

targetGroupLayer = arcpy.mapping.ListLayers(mxd, "Actual", df)[0] 
# loop through list, adding each shapefile to group layer 
for shapefile in list_shapefiles: 
    addLayer = shapefile 
    arcpy.mapping.AddLayerToGroup(df, targetGroupLayer, addLayer, "TOP") 

mxd.saveACopy(r"D:\tes\Operation_2.mxd") 
相關問題