在Arcgis python(Arcpy)中选择具有指定名称的要素类

时间:2017-09-08 05:33:07

标签: python arcgis arcpy

我正在使用arcpy,我想提取一个名为" building"的特定要素类。嵌套在我工作区内的许多地理数据库中。

以下是代码:

import arcpy
import os

workspace = "C:/Wiley/P1/gis"
search = "Building"
outdir = "C:/Wiley/P1/gis/HK80.gdb"
fc = []

walk = arcpy.da.Walk(workspace, datatype="FeatureClass", type="Polygon")

for dirpath, dirnames, filenames in walk:
          for filename in filenames:
             if search == filename:
                     fc.append(os.path.join(dirpath, filename))
if fc:
     output = os.path.join(outdir, os.path.basename(search) + "_merge")
     arcpy.Merge_management(fc, output)

此代码成功。

但地理数据库中除了" Building"之外还有许多其他要素类。所以我稍微扩展了代码并尝试通过所有这些要素类循环merge命令:

    import arcpy
import os

#--------------------------
#example list workspace
arcpy.env.workspace = "C:/Wiley/P1/gis/HKU_Job69.gdb"

#Generate exmaple list dataset
datasets = arcpy.ListDatasets(feature_type='All')
datasets = [''] + datasets if datasets is not None else []
fc_list = []

#--------------------------

#where all the gdb is nested
workspace = "C:/Wiley/P1/gis"

#define output
outdir = "C:/Wiley/P1/gis/HK80.gdb"

#List of Feature classes
fc = []

#define walk for looping
walk = arcpy.da.Walk(workspace, datatype="FeatureClass", type="Any")

for ds in datasets:
     for fc_example in arcpy.ListFeatureClasses(feature_dataset=ds):
        fc_list.append(fc_example)


for f in fc_list: #Loop through the list   
   for dirpath, dirnames, filenames in walk:        
        for filename in filenames:
           if f == filename:
                     fc.append(os.path.join(dirpath, filename))
   if fc:
        output = os.path.join(outdir, os.path.basename(search) + "_merge")
        arcpy.Merge_management(fc, output)

这是我撞墙的地方。这段代码有什么问题吗?我是Python的新手,所以对于训练有素的人来说,你们可以立即发现逻辑中的错误。 f变量似乎根本没有循环。

1 个答案:

答案 0 :(得分:0)

尝试整理缩进 - 例如,您不需要缩进导入arcpy的第一行。此外,在您的第一个脚本(正在运行的脚本)中,arcpy.Merge_management工具不在循环中。在第二个(不工作)脚本中,它位于fc_list循环中,如果我正确理解了脚本的逻辑,则不需要。

你也可以尝试在fc_list循环中添加一个print语句来查看它是否正在运行 - 如下所示:

for f in fc_list: #Loop through the list   
    for dirpath, dirnames, filenames in walk:        
        for filename in filenames:
            print filename
            if f == filename:
                fc.append(os.path.join(dirpath, filename))
                print 'appended'
            else:
                print 'nope!'
    print 'done with walk'

if fc:
    output = os.path.join(outdir, os.path.basename(search) + "_merge")
    arcpy.Merge_management(fc, output)