Python script for Layer to KML

4909
2
08-24-2010 12:07 PM
CraigMalkmes
New Contributor
Howdy,

I've been working on a Python script to convert a bunch of .shp files to .kmz files using gp.MakeFeatureLayer_management, followed by gp.LayerToKML_3d. It's been pretty straighforward and the script only requires a few lines of code. However, I'm getting stuck when it comes to maintaining original filenames. I'd like to have the numbers correspond, i.e. 'poly15.shp' is spatially the same in ArcMap as 'poly15.kmz' is in Google Earth. As of now, the script succeeds in converting the files, however they don't match up.

Windows stores its files in numerical order, i.e. 'poly1, poly2, poly3, etc.' ... however, I see in ArcCatalog that files are listed in the form of 'poly 0, poly 1, poly 10, poly 100, etc.' . Does this have something (everything) to do with it? I decided to use variable 'i' to append each name, as the two geoprocesses ask you to name the file as part of the parameters. I'm using my Python knowledge from college here . . . there's got to be an easy fix that I'm just not wrapping my brain around.



Here's what I've got:



# Import system modules
import sys, string, os, arcgisscripting, glob

# Create the Geoprocessor object
gp = arcgisscripting.create()

# Check out any necessary licenses
gp.CheckOutExtension("3D")

# Load required toolboxes...
gp.AddToolbox("C:/Program Files/ArcGIS/ArcToolbox/Toolboxes/Data Management Tools.tbx")
gp.AddToolbox("C:/Program Files/ArcGIS/ArcToolbox/Toolboxes/3D Analyst Tools.tbx")

path = 'C:/Craig/Working/07282010/tiles'
i = 0
for infile in glob.glob(os.path.join(path, '*.shp')):
   
    # Local variables...
    poly_Layer = "poly_Layer" + str(i)
    poly_kmz = "C:\\Craig\\Working\\07282010\\KML\\poly" + str(i) + ".kmz"
    tiles = "C:\\Craig\\Working\\07282010\\tiles"

    # Process: Make Feature Layer...
    gp.MakeFeatureLayer_management(infile, poly_Layer, "", tiles)

    # Process: Layer To KML...
    gp.LayerToKML_3d(poly_Layer, poly_kmz, "20000", "false", "DEFAULT", "1024", "96")

    i = i + 1



I'm assuming I need to get rid of the i variable as well as the str() naming...but how do I get the processes to automatically name the files based on the original file being converted? Right now, 'poly1.shp' is in Tennessee, and 'poly1.kmz' is in New York. It's not as if it's a projection problem, it's just that the loop is converting files in an order that is different from what I'd expect.

Thanks,

CM
0 Kudos
2 Replies
JasonScheirer
Occasional Contributor III
poly_kmz = os.path.join("C:\\Craig\\Working\\07282010\\KML\\", os.path.splitext(os.path.basename(infile))[0] + '.kml')
0 Kudos
CraigMalkmes
New Contributor
Jason,

Makes sense... it's iterating correctly now.

Much appreciated,

Craig
0 Kudos