繁体   English   中英

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

[英]Python variable working outside of function, but not inside

我有一个问题,我试图将要素类复制到地理数据库。 我循环遍历文件夹中的所有要素类并仅复制面要素类。 我的问题是,当我复制第一个面要素类时,它将其重命名为'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"

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

我找到了问题的答案。 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."

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

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

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

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

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM