检查数据是否存在

AllSource 1.4    |

要在脚本中检查是否存在数据,请使用 Exists 函数。

Exists(dataset)

测试执行时当前工作空间中是否存在要素类、表、数据集、shapefile、工作空间、图层和其他文件。 函数返回指示元素是否存在的布尔值。

Exists 函数

检查地理数据是否存在时,请使用 Exists 函数,因为它可以识别目录路径。 目录路径是只有 ArcGIS 才能识别的路径名称。 例如:D:\Data\Final\Infrastructure.gdb\EastValley\powerlines 是指文件地理数据库 Infrastructure 中的 EastValley 要素数据集中找到的 powerlines 要素类。 就 Windows 操作系统而言,这不是有效的系统路径,因为 Infrastructure.gdb(文件夹)不包含名为 Infrastructure 的文件。 简而言之,Windows 不了解要素数据集或要素类,因此您无法使用 Python 存在函数,例如 os.path.exists。 当然,ArcGIS 中每个组件都知道如何处理目录路径。 也可以使用通用命名约定 (UNC) 路径。

import arcpy

arcpy.env.workspace = "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 = "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) 来更改此行为。 如果在 overwriteOutputFalse 时尝试覆盖,则会导致工具失败。