ArcGIS, Python and File Exists

November 26, 2008

I use the script in models to test to see if output exists, if it exists, delete the files.  Otherwise do nothing.  Rather than include coding in my models for when the file does not exist, I have been create a “Step 2″ model.  I prefer creating multiple small models so that I can get each step working.  Someone asked, “Why not recombined once all the steps work?”  My answer is that I still find it easier to keep everything compartmentalized in case I want to tweak latter or try to streamline coding.

fileexists1

#**********************************************************************
# Description:
# Tests if a Dataset/Feature Layer and outputs two booleans:
#   Exists – true if the Dataset exists, false if it doesn’t exist
#   Not_Exists – true if the Dataset doesn’t exist, false if it does exist
#                (the logical NOT of the first output).
#
# Arguments:
#  0 – DataSet Name
#  1 – Exists (boolean – see above)
#  2 – Does Not Exists (boolean – see above)
#
# Created by: ESRI
# Modified By Mike Wilson (3/28/08)
#**********************************************************************

# Standard error handling – put everything in a try/except block
#
try:

# Import system modules
import sys, string, os, arcgisscripting

# Create the Geoprocessor object
gp = arcgisscripting.create()

# Get input arguments – DataSet Name
#
in_Dataset = gp.GetParameterAsText(0)

# First check that the DataSet exists
#
if gp.Exists(in_Dataset):
gp.SetParameterAsText(1, “True”)
gp.SetParameterAsText(2, “False”)
else:
gp.SetParameterAsText(1, “False”)
gp.SetParameterAsText(2, “True”)

# Handle script errors
#
except Exception, errMsg:

# If we have messages of severity error (2), we assume a GP tool raised it,
#  so we’ll output that.  Otherwise, we assume we raised the error and the
#  information is in errMsg.
#
if gp.GetMessages(2):
gp.AddError(GP.GetMessages(2))
else:
gp.AddError(str(errMsg))
#**********************************************************************

I modified this script quite a while ago and use it often.  I believe it is based on the “Field Check script” and the article “Branching: Implementing if-then-else logic“.  I apologize for note being more specific, but I misplaced my notes.  If I have improperly cited the origin, let me know.  I coded this prior to my start of using Evernote.