我在尝试将要素类复制到地理数据库中时遇到问题。我遍历了文件夹中的所有要素类,并且仅复制了多边形要素类。我的问题是,当我复制第一个面要素类时,它将重命名为“ shp”,然后也尝试命名第二个“ shp”。变量fcname
返回复制功能之外的完整要素类名称(“ counties.shp”和“ new_mexico.shp”),但在功能内部无法正常工作。
下面的代码注释了要运行的功能,以测试fcname
变量。文件夹中有五个要素类,其中两个是面要素类。取消注释时,代码将一直贯穿第一个面要素类,其中fcname
会生成“ shp”而不是“ counties.shp”。由于第二个要素类的功能相同,因此会导致错误,因为gdb
中已经存在“ shp”。
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."