ArcGIS Pro脚本工具(14)——裁剪文件夹或数据库(保留文件夹结构)

有网友私信,希望能做这个功能,安排。。。

作为规划人,很自然就能想到这个功能的应用场景。比如有一个文件夹,包含了一个县的各种shp要素类和gdb数据库,现在需要从中抽取一个乡镇的范围出来,并且还需要做成与原来文件夹一致的结构。

让我们先看看ArcGIS的裁剪工具

96e3013bcf2345b9ac7efb37e86cb171.png

ArcGIS的裁剪工具

使用自带的裁剪工具,虽然能批处理裁剪多个要素类,但是想做成原来一致的结构还是要费一番功夫。如果能裁剪整个文件夹,能省下很多组织文件的功夫。

Python脚本

import os
import arcpy

raw_dir = arcpy.GetParameterAsText(0)

clip_features = arcpy.GetParameterAsText(1)

new_dir = arcpy.GetParameterAsText(2)

arcpy.management.Copy(raw_dir, new_dir)

workspaces = []

for filepath, dirnames, filenames in os.walk(raw_dir):
    workspaces.append(filepath)

for ws in workspaces:
    arcpy.env.workspace = ws
    fcs = arcpy.ListFeatureClasses()
    for fc in fcs:
        name = ws.replace(raw_dir, new_dir)+"\\"+fc
        arcpy.analysis.Clip(fc, clip_features, name)

    datasets = arcpy.ListDatasets()
    for ds in datasets:
        fcs = arcpy.ListFeatureClasses(feature_dataset=ds)
        arcpy.env.workspace = ds
        for fc in fcs:
            name = ws.replace(raw_dir, new_dir)+"\\"+ds+"\\"+fc
            arcpy.analysis.Clip(fc, clip_features, name)

参数设置

daca33e11b7b47379c0b17e04f2a4f7c.png

验证代码(可根据输入填充参数)

class ToolValidator:
    # Class to add custom behavior and properties to the tool and tool parameters.

    def __init__(self):
        # set self.params for use in other function
        self.params = arcpy.GetParameterInfo()

    def initializeParameters(self):
        # Customize parameter properties. 
        # This gets called when the tool is opened.
        return

    def updateParameters(self):
        # Modify parameter values and properties.
        # This gets called each time a parameter is modified, before 
        # standard validation.
        if self.params[0].altered or self.params[1].altered:
            if self.params[0].value and self.params[1].value and not self.params[2].value:
                raw_dir = self.params[0].valueAsText
                raw_path = os.path.dirname(raw_dir)
                raw_name = os.path.splitext(os.path.basename(raw_dir))[0]
                raw_ext = os.path.splitext(os.path.basename(raw_dir))[1]
                
                clip_features = self.params[1].valueAsText
                clip_name = os.path.splitext(os.path.basename(clip_features))[0]
                
                new_dir = raw_path+"\\"+raw_name+"_"+clip_name+raw_ext
                self.params[2].value = new_dir
        return

    def updateMessages(self):
        # Customize messages for the parameters.
        # This gets called after standard validation.
        return

    # def isLicensed(self):
    #     # set tool isLicensed.
    #     return True

效果演示

606845101594418c95afa31494549f02.gif

 

 


版权声明:本文为baidu_28157641原创文章,遵循CC 4.0 BY-SA版权协议,转载请附上原文出处链接和本声明。