Creating a new Python script
To retain Python code, you create Python files (.py). These files are ASCII files that contain Python statements.
- In the Python Integrated Development Environment (IDE) of your choice, create a new script and add the following lines at the top of your script:
- An input workspace defining the set of feature classes to process
- A feature class to be used by the Clip tool as the area to be clipped from an input feature class
- An output workspace where the results of the Clip tool will be written
- An XY tolerance that will be used by the Clip tool
- Add the following code to your script to define and set variables based on the user-defined values passed to the script at execution:
- Add the following error-handling statement and ArcPy's ListFeatureClasses() function to the script window:
- Add the following code:
- Add the following lines to complete the script:
- Add the following header to the top of your script:
- Save the script.
# Import ArcPy site-package and os modules
import arcpy
import os
This imports the ArcPy site-package and operating system module os to the script. The os module provides easy access to the most fundamental tools of the operating system. Some of the os module's file name manipulation methods are used in this script.
This script will have the following four arguments so it can be used generically:
# Set the input workspace
arcpy.env.workspace = arcpy.GetParameterAsText(0)
# Set the clip featureclass
clipFeatures = arcpy.GetParameterAsText(1)
# Set the output workspace
outWorkspace = arcpy.GetParameterAsText(2)
# Set the XY tolerance
clusterTolerance = arcpy.GetParameterAsText(3)
try:
# Get a list of the featureclasses in the input folder
fcs = arcpy.ListFeatureClasses()
Python enforces indentation of code after certain statements as a construct of the language. The try statement defines the beginning of a block of code that will be handled by its associated exception handler, or except statement. All code within this block must be indented. Python uses try/except blocks to handle unexpected errors during execution. Exception handlers define what the program should do when an exception is raised by the system or by the script itself. Exception handling also allows the script to exit gracefully and return informative messages instead of causing a system error.
The ListFeatureClasses() function returns a list of feature class names in the current workspace. The workspace defines the location of your data and where all new data will be created unless a full path is specified. The workspace has already been set to the first argument's value. A for loop is used to walk through each feature class contained in the list.
for fc in fcs:
# Validate the new feature class name for the output workspace.
featureClassName = arcpy.ValidateTableName(fc, outWorkspace)
outFeatureClass = os.path.join(outWorkspace, featureClassName)
# Clip each feature class in the list with the clip feature class.
# Do not clip the clipFeatures, it may be in the same workspace.
if fc != os.path.basename(clipFeatures):
arcpy.Clip_analysis(fc, clipFeatures, outFeatureClass,
clusterTolerance)
When there are no more names in the list, the for loop ends. The ValidateTableName() function is used to ensure the output name is valid for the output workspace. Certain characters, such as periods or dashes, are not allowed in geodatabases, so this method returns a name with valid characters in place of invalid ones. It also returns a unique name so no existing data is overwritten.
The os.path.basename method is used to manipulate the clip feature class's path, so only the feature class name is evaluated in an expression, not the entire path. The Clip tool is accessed as an ArcPy function, using the various string variables as parameter values.
except Exception as err:
arcpy.AddError(err)
print err
The except statement is required by the earlier try statement; otherwise, a syntax error occurs. If an error occurs during execution, the code within the except block is executed. Any error messages are added using the AddError() function in case the script is run from a script tool. All error messages are also printed to the standard output in case the script is run outside a tool.
"""-----------------------------------------------------------------------------
Script Name: Clip Multiple Feature Classes
Description: Clips one or more shapefiles
from a folder and places the clipped
feature classes into a geodatabase.
Created By: Insert name here.
Date: Insert date here.
-----------------------------------------------------------------------------"""
When naming variables, remember that Python is case sensitive, so clipFeatures is not the same as ClipFeatures.
GetParameterAsText() is used to receive arguments. If a script uses defined dataset names and parameter values, it may not need to use the GetParameterAsText() function.
Statements that end with a colon indicate the beginning of indented code. Python does not use braces, brackets, or semicolons to indicate the beginning or end of a block of code. Python instead uses the indentation of the block to define its boundaries. This results in code that is easy to read and write.
The completed script:
"""-----------------------------------------------------------------------------
Script Name: Clip Multiple Feature Classes
Description: Clips one or more shapefiles
from a folder and places the clipped
feature classes into a geodatabase.
Created By: Insert name here.
Date: Insert date here.
-----------------------------------------------------------------------------"""
# Import ArcPy site-package and os modules
import arcpy
import os
# Set the input workspace
arcpy.env.workspace = arcpy.GetParameterAsText(0)
# Set the clip featureclass
clipFeatures = arcpy.GetParameterAsText(1)
# Set the output workspace
outWorkspace = arcpy.GetParameterAsText(2)
# Set the XY tolerance
clusterTolerance = arcpy.GetParameterAsText(3)
try:
# Get a list of the featureclasses in the input folder
fcs = arcpy.ListFeatureClasses()
for fc in fcs:
# Validate the new feature class name for the output workspace.
featureClassName = arcpy.ValidateTableName(fc, outWorkspace)
outFeatureClass = os.path.join(outWorkspace, featureClassName)
# Clip each feature class in the list with the clip feature class.
# Do not clip the clipFeatures, it may be in the same workspace.
if fc != os.path.basename(clipFeatures):
arcpy.Clip_analysis(fc, clipFeatures, outFeatureClass,
clusterTolerance)
except Exception as err:
arcpy.AddError(err)
print err