将.dbf与.shp连接 - 然后计算字段脚本 - 错误处理,脚本在无连接时退出
我写了一个简单的脚本,用来把一个 .dbf 文件和一个 .shp 文件合并,然后计算一些字段。这个脚本运行得很好,但如果因为某种原因没有成功合并,就会出现一个错误,这个错误会让脚本停止运行,导致它在处理我工作目录里的其他 .dbf 和 .shp 文件之前就结束了。请问我该怎么做才能让脚本忽略那些没有成功合并的 .shp 文件,继续处理目录里的其他 .shp 文件呢?
错误信息:在第20行,gp.CalculateField_management("parcs", "APN2", "[TAX.PARCEL_ID]")执行出错:ERROR 999999:执行函数时出错。使用了无效的SQL语句。
以下是脚本:
# Create the geoprocessor object
gp = arcgisscripting.create(9.3)
gp.OverWriteOutput = True
# Set the workspace. List all of the folders within
gp.Workspace = "C:\JoinCalculateBatch"
fcs = gp.ListWorkspaces("*","Folder")
for fc in fcs:
print fc
gp.MakeFeatureLayer(fc + "\\Parcels.shp", "parcs")
joinTable = (fc + "\\TAX.dbf")
gp.AddJoin_management("parcs", "APN", joinTable, "PARCEL_NUM")
gp.CalculateField_management("parcs", "APN2", "[TAX.PARCEL_ID]")
gp.CalculateField_management("parcs", "SIT_FULL_S", "[TAX.SITADDRESS]")
3 个回答
你有办法使用arcpy(arcGIS 10)吗?
我知道在arcGIS 10里面,有一个叫做Join_Field的工具,它在arcGIS的工具箱里。你可以用这个工具把dbf文件里的所有字段根据某种唯一的ID字段,连接到shp文件上。
你可以试试下面的代码,这段代码会在你进行连接或计算字段的时候,自动忽略任何错误,并继续执行循环的下一次。如果你只是写一个临时用的脚本,这样做可能没问题,但如果你打算将这个脚本在未来使用或者分享给别人,就应该弄清楚为什么
不过,光凭这些信息,没看到你的表格和形状文件,很难确切知道是什么导致了你的错误。你可以试着把你的Parcels.shp和Tax.dbf文件导入到ArcMap中,进行连接,然后使用计算字段工具,看看你的参数是否正确。
for fc in fcs:
print fc
gp.MakeFeatureLayer(fc + "\\Parcels.shp", "parcs")
joinTable = (fc + "\\TAX.dbf")
try:
gp.AddJoin_management("parcs", "APN", joinTable, "PARCEL_NUM")
gp.CalculateField_management("parcs", "APN2", "[TAX.PARCEL_ID]")
gp.CalculateField_management("parcs", "SIT_FULL_S", "[TAX.SITADDRESS]")
except:
print 'Join or Calculate Field did not work for %s.' % (fc)
你可能还想试试下面的语法,这段代码直接来自于文档。
gp.CalculateField_management("parcs", "APN2", "!TAX.PARCEL_ID!", "PYTHON")
我没有办法使用装有ArcGIS的Windows电脑,所以没法测试这个。不过一般来说,你需要捕捉一个异常,然后决定怎么处理它……比如说:
# Create the geoprocessor object
gp = arcgisscripting.create(9.3)
gp.OverWriteOutput = True
# Set the workspace. List all of the folders within
gp.Workspace = "C:\JoinCalculateBatch"
fcs = gp.ListWorkspaces("*","Folder")
for fc in fcs:
print fc
gp.MakeFeatureLayer(fc + "\\Parcels.shp", "parcs")
joinTable = (fc + "\\TAX.dbf")
try:
gp.AddJoin_management("parcs", "APN", joinTable, "PARCEL_NUM")
gp.CalculateField_management("parcs", "APN2", "[TAX.PARCEL_ID]")
gp.CalculateField_management("parcs", "SIT_FULL_S", "[TAX.SITADDRESS]")
except ExecuteError:
print 'Could not join', fc
我上面写的内容是行不通的。ExecuteError
并不是一个普通的Python错误,它是ArcGIS特有的错误模块。你可能需要用类似这样的方式:
except gp.ExecuteError:
...
不过,我对Arc不够熟悉,没法在这方面帮到你……