检查数据是否存在
要在脚本中检查是否存在数据,请使用 Exists 函数。 Exists 函数可以测试当前工作空间中是否存在要素类、表、数据集、shapefile、工作空间、图层和其他文件。 函数返回指示元素是否存在的布尔值。
使用 Exists 函数测试是否存在 ArcGIS 数据。 Exists 适用于目录路径,ArcGIS 可识别此类路径,但操作系统无法识别。 目录路径可以指向地理数据库内部的要素数据集和要素类等项目。 例如,虽然 Windows 无法解析,但 d:\data\infrastructure.gdb\powerlines 是有效的 ArcGIS 路径。 Windows 将 infrastructure.gdb 视作文件夹,无法识别其中的地理数据库结构,因此 Python 文件系统函数(例如 os.path.exists)无法正常工作。
因为 ArcGIS 能够识别目录路径,所以应该改用 Exists 函数。 系统还支持 UNC 路径。
import arcpy
arcpy.env.workspace = r"d:\St_Johns\data.gdb"
fc = "roads"
# Clip a roads feature class if it exists
if arcpy.Exists(fc):
arcpy.analysis.Clip(fc, "urban_area", "urban_roads")
提示:
Exists 函数遵循当前工作空间环境,支持仅指定基本名称。
如果数据保留在企业级地理数据库中,则名称必须完全限定。
import arcpy
arcpy.env.workspace = r"Database Connections\Bluestar.sde"
fc = "ORASPATIAL.Rivers"
# Confirm that the feature class exists
if arcpy.Exists(fc):
print("Verified {} exists".format(fc))
在脚本中,所有工具的默认行为是不覆盖任何已存在的输出。 可以通过将 overwriteOutput 属性设置为 True (arcpy.env.overwriteOutput = True) 来更改此行为。 如果在 overwriteOutput 为 False 时尝试覆盖,则会导致工具失败。