How do I check whether a file with a user-defined prefix already exists, using the while loop and if it is a case to request another prefix?
2 Answers 2
Use arcpy.Exists()
if arcpy.Exists(r"MyFeatureClass"):
print "Feature Class Exists"
else:
print "Feature Class Doesn't Exist"
Additionally, look into arcpy.CreateUniqueName()
to generate a new output name if the one you want to use already exists
uniqueName = arcpy.CreateUniqueName(r"MyFeatureClass")
arcpy.Buffer_analysis(r"InputFC", uniqueName, "10 Meters")
Based on what I think your code is doing, try this:
sbgfl = "sbg_fluesse"
bufferwerte = raw_input("Enter buffer in m [split with space bar]")
bufferwerte_2 = bufferwerte.split()
praefix = raw_input("Enter prefix")
for buffer_size in bufferwerte_2:
uniqueName = arcpy.CreateUniqueName(praefix + str(buffer_size))
arcpy.Buffer_analysis(sbgfl, uniqueName, buffer_size)
This will add a suffix number to the end of your output name to make it unique if the output name already exists.
e.g. if praefix = "roads"
and buffer_size = 10
, and roads10
already exists, the arcpy.CreateUniqueName()
will create a output name of roads10_0
to make it unique.
And to include a notice to the user that the filename is different:
for buffer_size in bufferwerte_2:
if arcpy.Exists(praefix + str(buffer_size)):
print "Already exists, changing name"
uniqueName = arcpy.CreateUniqueName(praefix + str(buffer_size))
print "Output name = {0}".format(uniqueName)
arcpy.Buffer_analysis(sbgfl, uniqueName, buffer_size)
Tasks such as checking for shapefiles or raster data are much more efficient using built-in Python modules. For example:
However, if you need to check for the existance of data within Esri Geodatabases, use the arcpy.Exists()
command as Midavalo highlights in his answer.