0

我正在尝试遍历多个目录和多个 GDB 以创建要素类列表。我遇到的问题是,当我尝试从列表中删除某些要素类时,脚本只是被忽略了,或者我收到一个错误,提示 x 在 list.(x) 中不存在。要素类名称的问题在于它有 3 个字母,每个 GDB 都是唯一的,同时还有 2 个其他标准组件。

像这样的东西:

目录 1 > 目录 1.gdb > 形状 > fc_dir1_feature

&

目录 2 > 目录 2.gdb > 形状 > fc_dir2_feature

等等...

我在用

for dirpath, dirnames, filenames in arcpy.da.Walk(in_workspace, datatype="FeatureClass",type="Polygon"):
if "dir1" in dirnames:
    dirnames.remove('dir1')

这可以很好地从 GDB 中删除要素数据集,并扩展其中的所有要素类。但我不能只删除特定的要素类。

谢谢你的帮助。

4

1 回答 1

1

假设 arcpy.da.Walk 像 os.walk 一样工作(也就是说,从 dirnames 中删除一个目录会停止进入该目录),您应该添加另一个 for 循环来迭代 dirnames 并应用您的过滤器。请注意,我复制了目录名,这样我就可以调用 remove 而不会弄乱迭代器。

for dirpath, dirnames, filenames in arcpy.da.Walk(in_workspace, datatype="FeatureClass",type="Polygon"):
    # remove subdirectories that match pattern so they will not be walked
    for dirname in dirnames[:]:
        if 'dir1' in dirname:
            dirnames.remove(dirname)

来自ArcGIS Resources,您可以使用正则表达式以几种不同的方式过滤文件名。以下是删除通配符插槽中包含“abc”、“def”或“ghi”的文件的正则表达式示例:

import arcpy
import os
import re

workspace = "c:/data"
feature_classes = []

# i dont like abc, def or ghi features so I have a regex to match them
filter_classes_re = re.compile('fc_(abc|def|ghi)_feature$')

for dirpath, dirnames, filenames in arcpy.da.Walk(workspace,
                                                  datatype="FeatureClass",
                                                  type="Polygon"):
    for filename in filenames:
        # only add to feature list if it doesn't match the bad guys
        if filter_classes_re.match(filename) is None:
            feature_classes.append(os.path.join(dirpath, filename))


# alternately, i could extract the wildcard part and compare it outside
# of the regex ... but this will be slower

filter_classes_re = re.compile('fc_(.*?)_feature$')

for dirpath, dirnames, filenames in arcpy.da.Walk(workspace,
                                                  datatype="FeatureClass",
                                                  type="Polygon"):
    for filename in filenames:
        # extract the wildcard part
        match = filter_classes_re.match(filename)
        if match:
            matched = match.group(1)
        else:
            matched = ''
        if matched not in ('abc', 'def', 'ghi'):
            feature_classes.append(os.path.join(dirpath, filename))
于 2013-05-23T16:06:26.910 回答