# Name: BatchKML_to_GDB.py
# Description: Converts a directory of KMLs and copies the output into a single
# fGDB. A 2 step process: first convert the KML files, and then
# copy the feature classes.
# Import system modules
import arcpy
import os
# Set workspace (where all the KMLs are)
arcpy.env.workspace = "C:/VancouverData/KML"
# Set local variables and location for the consolidated file geodatabase
out_location = "C:/WorkingData/fGDBs"
gdb = 'AllKMLLayers.gdb'
gdb_location = os.path.join(out_location, gdb)
# Create the master File Geodatabase
arcpy.management.CreateFileGDB(out_location, gdb)
# Convert all KMZ and KML files found in the current workspace
for kmz in arcpy.ListFiles('*.KM*'):
print("CONVERTING: {0}".format(os.path.join(arcpy.env.workspace, kmz)))
arcpy.conversion.KMLToLayer(kmz, out_location)
# Change the workspace to fGDB location
arcpy.env.workspace = out_location
# Loop through all the file geodatabases within the workspace
wks = arcpy.ListWorkspaces('*', 'FileGDB')
# Skip the Master GDB
wks.remove(gdb_location)
for fgdb in wks:
# Change the workspace to the current file geodatabase
arcpy.env.workspace = fgdb
# For every feature class inside, copy it to the Master and use the name
# from the original fGDB
feature_classes = arcpy.ListFeatureClasses('*', '', 'Placemarks')
for fc in feature_classes:
print("COPYING: {} FROM: {}".format(fc, fgdb))
fcCopy = os.path.join(fgdb, 'Placemarks', fc)
arcpy.conversion.FeatureClassToFeatureClass(
fcCopy, gdb_location, fgdb[fgdb.rfind(os.sep) + 1:-4])