I'm using ArcGIS Pro 2.9.5. I'm not a newbie but am having trouble with script tool output. I have a custom tool where I want the output feature classes to be written to a file geodatabase that is specified in a parameter of my script tool. The parameter type is Workspace, Direction is Output, and there is a Filter for Workspace | Local Database. I have the setting "Allow geoprocessing tools to overwrite existing datasets" checked because I need that to overwrite feature classes and text file outputs, if they exist. If I change the direction to Input this works, but I am trying to have the flexibility in my script to use an existing gdb if it exists, and create the gdb if it doesn't already exist. Maybe that is important for understanding my issue.
In my tool dialog if I browse to and select an existing geodatabase, I get the warning 000725 that the dataset already exists. In my mind I think this is ok, because I will be writing feature classes to that gdb. But if I run the tool, the gdb is deleted. I can create it again via arcpy and then it is recognized, but that doesn't work for my use case. I would expect a feature class to be overwritten but not the gdb which holds it. I've had the same problem when I want to write out csvs and other data to a folder that already exists - the whole folder is deleted when I hit run! When I run the same code through the Python window, this behavior doesn't happen - it recognizes that the gdb already exists.
I thought maybe it was arcpy.Exists() screwing up so I added checks using os.path.exists() and same results, so I'm at a loss. Can I not write geoprocessing output to an existing geodatabase specified in a script tool parameter? It seems like I'm missing something fundamental here...
This is my code to try to document what is happening.
import arcpy
import os
def log(message):
arcpy.AddMessage(message)
print(message)
# parameter 0 details:
# Type = Workspace
# Direction = Output
# Filter = Workspace | Local Database
geodatabase = arcpy.GetParameterAsText(0)
log(f"Parameter 0 = {geodatabase}")
gdb_dir = os.path.dirname(geodatabase)
gdb_name = os.path.basename(geodatabase)
gdb_files = [os.path.join(gdb_dir, file) for file in os.listdir(gdb_dir) if file.endswith(".gdb")]
log(r"os.listdir finds the following gdbs:")
log(gdb_files)
if arcpy.Exists(geodatabase):
log("Geodatabase exists (arcpy)")
else:
log("Geodatabase doesn't exist (arcpy)")
if os.path.exists(geodatabase):
log("Geodatabase exists (os.path)")
else:
log("Geodatabase doesn't exist (os.path)")
log("Now I will create the gdb via arcpy")
arcpy.management.CreateFileGDB(gdb_dir, gdb_name)
if arcpy.Exists(geodatabase):
log("Geodatabase exists (arcpy)")
else:
log("Geodatabase doesn't exist (arcpy)")
if os.path.exists(geodatabase):
log("Geodatabase exists (os.path)")
else:
log("Geodatabase doesn't exist (os.path)")
Any advice would be greatly appreciated.