假设 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))