Tuesday, May 17, 2011

Checking the Existence of Data

To check if data exists using the arcpy module, use the Exists().  This function tests for the existence of feature classes, tables, data sets, shapefiles, workspaces, layers, and other files in the current workspace at the time of execution.  The function will return a Boolean value (true/false) to let the end user know if the file exists.

Example: Check for Existences

import arcpy
from arcpy import env

env.workspace = r"c:\temp"
fc = sample.shp
if arcpy.Exists(fc):
   print "The sample.shp does exist"
else:
   print "The sample.shp does not exist"


Note
By default, when scripting, the results of any script or existing data is not to overwrite the data. To change that behavior, set the env.overwriteOutput to True. If data exists and the overwrite property is not set, it could cause an error to the thrown.

4 comments:

SD said...

This function is indeed useful but it can add unnecessary time to your script and affect performance. If you simply want your script to stop if data does not exist, just let the function attempting to use that data as input raise the exception that data does not exist. This removes the unnecessary call to Exists().

Andrew said...

Valid, but you don't want to always have your script/process end just because the data exists. This is a really basic example, and sometimes you might just want to rename the data, move to a new directory, etc...

Jim Landwehr said...

Despite using this overwrite, I am still getting an ERROR 000258...Output already exists. My code snippet is:

# Import arcpy module
print "Starting Conversion"
import arcpy
import arcgisscripting
gp = arcgisscripting.create(10.0)
gp.OverWriteOutput = 1

Andrew said...

Do not use import arcgisscripting if you are using arcpy.

So for arcpy module it works like this:
import arcpy
from arcpy import env
env.overwriteOutput = True