[GIS] Python script to check if feature class exists in geodatabase if not convert feature class to feature class

arcpy

I would like to check in one geodatabase and list the feature classes that are in it; check another geodatabsae for the list of feature classes, if they do not exist in the 2nd geodatabase then execute feature class to feature class. If one does then just skip. How can this be done with Python? Here is what I have so far. After I get my list how can I use arcpy.Exists to check another .gdb from my list, and if an element in the list does appear in that .gdb then skip it, however if it does not, then execute the function?

>>> import arcpy
... from arcpy import env
... import os
... 
... # Set the workspace for the ListFeatureClass function
... #
... env.workspace = r'C:\GIS_Data\MXDs\ServerMxdsR\working\gis_dev01.gdb'
... 
... # Use the ListFeatureClasses function to return a list of 
... #  shapefiles.
... #
... fcList = arcpy.ListFeatureClasses()

Best Answer

You want to try something like this

# Use the ListFeatureClasses function to return a list of 
#  shapefiles.
fcList = arcpy.ListFeatureClasses()

gdb2 = r'C:\GIS_Data\MXDs\ServerMxdsR\working\gis_dev02.gdb' # Your second geodatabase

for fc in fcList:
    secondFC = os.path.join(gdb2, fc)
    if arcpy.Exists(secondFC):
        print "{} exists, not copying".format(fc)
    else:
        arcpy.FeatureClassToFeatureClass_conversion(fc, gdb2, fc) # Copies feature class from first gdb to second gdb

Loops through your feature classes from your fcList, checks if they exist in your second gdb, and if they don't it performs arcpy.FeatureClassToFeatureClass_conversion to copy from gdb 1 to gdb 2.


To only copy feature classes if none of them exist in gdb 2, try this:

# Use the ListFeatureClasses function to return a list of 
#  shapefiles.
fcList = arcpy.ListFeatureClasses()

gdb2 = r'C:\GIS_Data\MXDs\ServerMxdsR\working\gis_dev02.gdb' # Your second geodatabase

anyFCExists = 0

for fc in fcList:
    secondFC = os.path.join(gdb2, fc)
    if arcpy.Exists(secondFC):
        anyFCExists = 1
        break

if not anyFCExists:
    for fc in fcList:
        secondFC = os.path.join(gdb2, fc)
        arcpy.FeatureClassToFeatureClass_conversion(fc, gdb2, fc) # Copies feature class from first gdb to second gdb
else:
    print "One of the feature classes already exists, so not copying any"

This loops through all feature classes, and if it finds any already exist, then it sets the anyFCExists flag. Then if the anyFCExists flag is not set then it loops through the feature classes and copies them all across.

Related Question