我想问一下使用ArcPy编写脚本来处理ArcGIS地图文档(MXD)中的要素数据。
我有一个文件夹,其中包含一些shapefile(shp)形式的特征数据。
我想创建一个ArcPy脚本,可以将上面的数据添加到MXD。我可以使用此脚本单独添加文件:
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")