[GIS] Building Python script that exports to several output files using ArcGIS Desktop

arcgis-9.3arcpy

I'm trying to build a Python Script that will receive one feature layer that will be clipped by several adjacent grid squares (each in a different shapefile) and output several shapefiles.

Now, I've built in the past a loop script that receives a list of files and does a single action on each file, like this:

for file in os.listdir(ws):
    if file.endswith(".shp") or file.endswith(".dxf") or file.startswith("str"):
    print file

But I'm not succeeding in making a loop that will receive the input shapefile and clip features (shapefiles) and EXPORT to different shapefiles (I mean how do I change the output shapefile's name for every grid square ?). Can someone show how it is done?

I'm using python 2.6 and Arcgis 9.3.1

Best Answer

I guess this depends on how often you want to run the script, whether or not you want to hard code in the clip grids and the output shapefiles.

Very simply, I'd have a dictionary, of clip_grid : output_shapefile, loop through that and spit out the output.

import arcgisscripting
#Create the geoprocessor
gp = arcgisscripting.create(9.3)

input_shape = "yourshapefile.shp" #<-- this single file will be clipped repeatedly

#grids and corresponding outputs go here
clip_dictionary = {"clipgrid1.shp":"output1.shp", "clipgrid2.shp":"output2.shp"}

for iter in clip_dictionary:
    #Clip_analysis (in_features, clip_features, out_feature_class, cluster_tolerance)
    gp.Clip_analysis(input_shape, iter, clip_dictionary[iter])

Hope that helps!

sys.argv is a possiblity if you wish to read in the arguments from the command line (or if you wish to add the script to the toolbox). You could also use getopt or optparse as well.

Assume that we have a script called clip_export.py, which we wish to pass a list of inputs. We could run the script like:

clip_export.py input_shape clipshape_1;clipshape_2;clipshape_3 output_folder

Note that this is similar to the input that is sent to a python script by Toolbox.

At any rate, you can read this in your script like so:

import sys

input_shape = sys.argv[1] #<-- Note that the 0th argument in sys.argv is the script name

clip_shape_list = sys.argv[2].split(';') #<-- splits the second argument on the semicolon into a python list

output_folder = sys.argv[3]

The from here run the rest of your script. As @Simon Norris shows below.

Again, hope this helps!