0

I am looking for my python code to check for the polycheck.gdb and if it is there delete and create a new one. Also, I would like to set my workspace to that database. Not sure if this is the right way to go about it.

# Import arcpy module
import arcpy
import os
import sys

from arcpy import env

arcpy.env.workspace = "C:/PolyCheck.gdb"

if arcpy.Exists("PolyCheck.gdb"):
    arcpy.Delete_management("PolyCheck.gdb")

arcpy.AddMessage(arcpy.GetMessages())

arcpy.CreateFileGDB_management("C:/output", "PolyCheck.gdb")


# Script arguments

I get this error:

ERROR 000732: File GDB Location: Dataset C:/output does not exist or is not supported Failed to execute (CreateFileGDB). Failed to execute (Script9).

2

Your script is a bit inconsistent in how it refers to the fGDB. Sometimes by full path, sometimes just using the database name alone.

To avoid this inconsistency, as well as to avoid errors due to typos, I usually assign the full path to a variable (eg, gdb). If you get a typo in your variable, its much easier to diagnose than a typo in a text string.

Then when you do need part of the path, you can use os.path.dirname() and os.path.basename() to get those parts.

Like this:

import arcpy, os, sys

gdb = "C:/output/PolyCheck.gdb"

if arcpy.Exists(gdb):
    arcpy.Delete_management(gdb)
    arcpy.AddMessage(arcpy.GetMessages())

if not os.path.exists(os.path.dirname(gdb)):
    os.mkdir(os.path.dirname(gdb))

arcpy.CreateFileGDB_management(os.path.dirname(gdb), os.path.basename(gdb))
arcpy.AddMessage(arcpy.GetMessages())

arcpy.env.workspace = gdb

Notice that the file (database) path is only referenced as a string literal ONCE in the entire script. That makes it impossible to type it incorrectly anywhere else, but is also makes it easier to make sure you use the full path everywhere, instead of accidentally leaving out the "C:/output" directory part of the path in some places.

This version of the script will also create the "C:/output" directory if it does not already exist (although it will still fail if there is a file, not a directory, at that location - but you can also test for that if you wish using os.path.isdir()).

NB: Deleting the database will still fail if it is use (ie, if there are any locks on its data or schema). Eg, if it has been opened in ArcMap, and ArcMap is still running (sometimes removing all the layers from your MXD, and even loading a new/blank MXD is not enough - you have to actually kill ArcMap).

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.