GEOG 485:
GIS Programming and Software Development

Lesson 2 Practice Exercise 4 Solution

PrintPrint

Solution:

import arcpy

try:
    arcpy.env.workspace =  "C:\\Data\\"

    template = "Precip2008Readings.shp"

    for year in range(2009,2013):
        newfile = "Precip" + str(year) + "Readings.shp"
        arcpy.CreateFeatureclass_management(arcpy.env.workspace, newfile, "POINT", template,
                                            "DISABLED", "DISABLED", template)

except:
    print (arcpy.GetMessages())

Explanation:

This script begins by initializing the geoprocessing object, setting the workspace, and selecting the toolbox that holds the desired tool. A reference to the shapefile to be copied is then stored in a variable. Because the idea is to create a copy of that shapefile for each year from 2009-2012, a logical approach is to set up a for loop defined with bounds of 'in range(2009,2013)'. (Recall that the upper end of the range should be specified as 1 higher than the actual desired end point.)

Within the loop, the name of the new shapefile is put together by concatenating the number held in the loop variable with the parts before and after that are always the same. The CreateFeatureClass tool can then be called upon, supplying the desired workspace for the output feature class, its name, its geometry type, the feature class to use as the schema template, whether the feature class should be configured to store m and z values, and finally a spatial reference argument.  Note from the documentation that the output feature class's spatial reference can be specified in a number of different ways and will be undefined if a spatial reference argument is not supplied.  (It does not automatically take on the spatial reference of the schema template feature class.)

Note also that the inconsistent casing CreateFeatureclass looks like a mistake on the part of Esri and is unfortunately required in this script.