Python变量在函数外部工作,但不在

时间:2016-04-04 12:15:53

标签: python arcpy

我有一个问题,我正在尝试将要素类复制到地理数据库中。我循环遍历文件夹中的所有要素类并仅复制面要素类。我的问题是,当我复制第一个面要素类时,它将其重命名为'shp',然后尝试命名第二个'shp'。变量fcname返回复制函数之外的完整要素类名称('counties.shp'和'new_mexico.shp'),但它在函数内部无法正常工作。

下面的代码具有我要运行的功能,用于测试fcname变量。文件夹中有五个要素类,其中两个是面要素类。取消注释后,代码将一直运行到第一个面要素类,其中fcname导致'shp'而不是'counties.shp'。对于导致错误的第二个要素类也是如此,因为{shp'已经存在于gdb中。

import arcpy

# Set initial variables with different pathnames available 
# whether I am working on my home or work computer

pathhome = "G:/ESRIScriptArcGIS/Python/Data/Exercise06"
pathwork = "C:/ESRIPress/Python/Data/Exercise06"
arcpy.env.workspace = pathwork
gdbname ="NewDatabase.gdb"

fclist = arcpy.ListFeatureClasses()

# Create new gdb
##arcpy.management.CreateFileGDB(path, gdbname)
newgdb = path + "/" + gdbname

# Loop through list
for fc in fclist:
    desc = arcpy.Describe(fc)
    fcname = desc.name
    outpath = newgdb + "/" + fcname

    # Check for polygon then copy
    if desc.shapeType == "Polygon":
        ##arcpy.management.CopyFeatures(fcname,outpath)
        ##print fcname + "copied."
        print fcname
    else:
        print "Not a polygon feature class"

感谢任何可以提供帮助的人!

2 个答案:

答案 0 :(得分:2)

我找到了问题的答案。 CopyFeatures不希望out_feature_class参数中包含完整的文件路径。我从文件路径的末尾剥离了“.shp”,它工作正常。

我也接受了Hector的建议并过滤到ListFeatureClasses参数中的多边形,但是,我仍然需要循环来遍历结果列表并复制每个要素类。

以下是生成的代码。

import arcpy

# Set initial variables with different pathnames available
# whether I am working on my home or work computer

pathhome = "G:/ESRIScriptArcGIS/Python/Data/Exercise06"
pathwork = "C:/ESRIPress/Python/Data/Exercise06"
arcpy.env.workspace = pathwork
gdbname ="NewDatabase.gdb"

fclist = arcpy.ListFeatureClasses("", "Polygon")

# Create new gdb
arcpy.management.CreateFileGDB(pathwork, gdbname)
newgdb = pathwork + "/" + gdbname

# Loop through list
for fc in fclist:
    desc = arcpy.Describe(fc)
    fcname = str(desc.name)
    outpath = newgdb + "/" + fcname.replace(".shp","")



    arcpy.management.CopyFeatures(fcname,outpath)
    print fcname + " has been copied."

答案 1 :(得分:1)

您的代码可能有错误。但是,我看到你的方法中的错误更明显。

如果您的目标是按形状过滤类,则可以使用feature_type函数接受的参数arcpy.ListFeatureClasses()

请参阅文档:http://pro.arcgis.com/en/pro-app/arcpy/functions/listfeatureclasses.htm

您不再需要使用for循环来过滤数据。

相关问题