Python Exercises
Python Exercises
Learning the
fundamentals of Python
and geoprocessing
Exercise 1
Introducing Python
Install the exercise data
Exercise data is provided online on the Esri Press book resources website at http://esripress.esri.com/bookresources. Copy the exercise data
to a hard drive.. The default path is C:\EsriPress\Python, but you can
change this during installation.
Next, you will select one of the options in ArcCatalog to make it easier
to recognize file types.
available at http://www.
esri.com/trydesktop because
it includes ArcGIS Spatial
Analyst.
>>> TIP
To make it easier to work with the exercise
data in this book, you can create a connection
to the data folder. In the Catalog window,
click the Connect to Folder button, browse
to C:\EsriPress\Python\Data, and click OK.
The shortcut will now appear under Folder
Connections in the Catalog tree.
ArcGIS 10.1 is designed to work with Python 2.7. At the final release
of ArcGIS 10.1, the most recent production version of Python 2.7 was
2.7.2, which is the version that is installed as part of a typical ArcGIS
10.1 installation. Versions of Python 2.7 will continue to evolve, but
the changes between these versions are so minor that ArcGIS 10.1
is expected to work with all versions of Python 2.7. The code in the
exercises will generally also work fine for other 2.x versions of Python,
including 2.6. However, when working with ArcGIS for Desktop, it
is recommended that you run the version of Python that is installed
with ArcGIS for Desktop. The code in the exercises will not work with
Python 3.x.
Note: It is possible to have multiple versions of Python on the same Windows computer.
If you already have a different version of Python installed in addition to the one that is
installed with ArcGIS for Desktop, be sure to use the version that is installed with ArcGIS
for Desktop to write and run the code in these exercises.
2 Close IDLE.
Install PythonWin
The exercises in the book use PythonWin as the editor application to
work with Python. The following steps walk you through the installation of PythonWin.
When you install PythonWin, it determines the version of Python that
is installed on your computer. The installation of ArcGIS 10.1 installs
Python version 2.7.2. The PythonWin installation then assumes you
have a program folder called Python 2.7however, the ArcGIS 10.1
installation creates a program folder called ArcGIS\Python 2.7. Therefore, you first need to create a program folder simply called Python 2.7.
1 For Windows XP: On the taskbar, right-click the Start button, and
then click Open All Users.
For Windows 7: On the taskbar, click the Start button, and then, on
the Start menu, right-click All Programs and click Open All Users.
Install PythonWin
Install PythonWin
7 On the second panel of the Setup wizard, notice that the installation
program found the Python version installed on your computer since
it is installed with ArcGIS. Accept the default directories and click
Next.
Install PythonWin
Install PythonWin
2 Make sure the pointer is placed directly following the prompt (>>>).
Type print "Hello World" and press Enter.
Notice that Python gives you the output of the line immediately. You
just entered a Python statement. The print statement is used to print the
value you supplied to the Interactive Window. The Interactive Window
has a prompt with three angle brackets (>>>). When you type a line
of code and press ENTER, that line is interpreted and run immediately. Notice that the interactive interpreter automatically recognizes
statements (such as print) and values (such as "Hello World") and
shows them in a different color. This is called syntax highlighting.
The IDLE interface is installed by default when Python 2.7 is installed.
Although it is a solid editor for working with Python, for the exercises
in this book you will use PythonWin because it has a number of advantages on the Microsoft Windows platform, in particular the integration
of the code debugger.
3 Close the IDLE editor by clicking File > Exit on the menu bar.
4 On the taskbar, click the Start button, and then, on the Start menu,
click All Programs > Python 2.7 > PythonWin.
>>> TIP
You want the Interactive Window to be open to see any messages that may appear
when you run a script. If you happen to close the Interactive Window, you can reopen
it by going to the PythonWin menu bar and clicking View > Interactive Window. There
is also a toggle button
Interactive Window.
Now you can add a new window where you can write a script.
7 On the PythonWin menu bar, click File > New.
8 On the New dialog box that appears, click Python Script and click
OK.
10
You now have two windows open within PythonWin. Code written in
the Script window can be saved, but code written in the Interactive
Window cannot be. Outputs from the Script window are printed to the
Interactive Window.
9 With the Script window active, on the PythonWin menu bar, click
File > Save As. On the Save As dialog box, navigate to the folder
C:\EsriPress\Python\Data\Exercise01 and save your file as hello.py.
The extension .py indicates the file is a Python script.
10 In the hello.py script window, type print "Hello World".
Pressing Enter, in this case, moves the cursor to the second line but does
not actually run the code because this is a script, and not the Interactive
Window. This allows you to keep writing code until you are ready to
run the script.
11 With the cursor still placed anywhere within the code in the hello.py
script window, click Run
. You can also click File > Run on the
PythonWin menu bar or press Ctrl+R.
11
Note: Before you can run a script, you must save it as a file with a .py extension. Once
you save it, every time you run the script, it is saved again automatically. So remember that
running a script automatically overwrites any earlier versions of the script that have the
same name.
13 Close the hello.py script. You can do this by clicking the X symbol of
the script window or by clicking File > Close on the PythonWin menu
bar with the script window active.
14 Close PythonWin by clicking the X symbol of the PythonWin window
or by clicking File > Exit on the menu bar.
12
13
ArcGIS for Desktop Help lists several key features that make the Python
window a valuable resource for running and experimenting with Python
commands and syntax. In ArcGIS 10.1 Desktop Help, on the Contents
tab, search for Using the Python window and youll find the following:
All Python functionality is exposed through the Python window.
Multiline commands that contain more than one geoprocessing tool
or geoprocessor method can be entered and executed.
Tools or functions that have already been entered and executed can
be recalled, edited, and re-executed.
Python commands or blocks of code can be loaded from existing
Python files.
Python commands or blocks of code can be saved to a Python or text
file to be reloaded later or used in a different environment.
Autocompletion functionality makes filling in geoprocessing tool
parameters quicker and easier than using tool dialog boxes.
Several of these features of the Python window will be explored in later
exercises.
14
Exercise 2
Geoprocessing in ArcGIS
Examine toolboxes and tools
ArcGIS software contains hundreds of tools, organized in toolboxes and
toolsets. There are two main ways to find the tools you need: search and
browse. You will practice both.
1 Start ArcMap. On the Standard toolbar, click the ArcToolbox button
. You can also open the ArcToolbox window from the menu bar by
clicking Geoprocessing > ArcToolbox.
Finding the tool you want can be a bit cumbersome if you are
not sure where to look, but with repetition you will start to
remember where the tools you use most are located. A similar approach to browsing can be accomplished in the Catalog
window.
3 Close the ArcToolbox window.
4 On the Standard toolbar, click the Catalog button
5 Expand the Toolboxes entry, and you can see two folders:
one for your custom toolboxes (My Toolboxes) and one for
system toolboxes. The organization of the system toolboxes
is the same as in the ArcToolbox window.
Now you can try using the Search window to find the geoprocessing tools.
6 Close the Catalog window.
7 On the Standard toolbar, click the Search window button
.
You can also open the Search window from the menu bar by
clicking Geoprocessing > Search For Tools.
16
Run a tool
Next, you will add some data so you can
start using some of the geoprocessing tools.
1 With ArcMap open, on the Standard
toolbar, click the Add Data button
.
On the Add Data dialog box, browse to
the folder C:\EsriPress\Python\Data\
Exercise02. Hold down Ctrl and click
basin.shp and soils.shp. Click Add.
This adds two shapefiles to your current
data frame in ArcMap. Check to see that
the extent of the soils shapefile is much
larger than the basin shapefile. You will use the Clip tool to reduce the
extent of the soils shapefile to match the basin shapefile.
Prior to running geoprocessing tools, you should set your environments.
Environments are parameters that control how a tool is run, but these
settings do not appear on the tool dialog box.
Run a tool
17
Run a tool
2 On the menu bar, click Geoprocessing > Environments. This brings up the Environment Settings
dialog box.
Notice the large number of categories, each with a
number of options under it. In this case, you will set
only the Workspace.
3 Click the Workspace entry to expand its options.
4 Click the Browse button next to Current Workspace.
Navigate to the C:\EsriPress\Python\Data\
Exercise02 folder and click Results. Click Add.
5 Repeat step 4 to set the Scratch Workspace.
18
8 For Input Features, select the soils shapefile from the drop-down list.
9 For Clip Features, select the basin shapefile from the drop-down list.
Notice that the Output Feature Class is automatically populated. The
path is determined by the environment settings (C:\EsriPress\Python\
Data\Exercise02\Results), and the file name is based on the inputs and
the name of the tool. You can use the Browse button to navigate to a different path. You can also change the path and output file name by typing in the text box.
10 Leave the XY Tolerance blank.
11 Click OK to run the tool. A progress bar that appears at the bottom of
the document on the ArcGIS for Desktop application status bar shows
that the tool is running. Once tool execution is complete, a small pop-up
notification briefly appears in the notification area, at the far right of the
taskbar.
The result of running the tool is a new shapefile called soils_Clip,
which is added to the ArcMap table of contents.
You can now explore the soils_Clip shapefile to confirm the result. You
can also review the execution of the tool by exploring the Results
window.
12 On the ArcMap menu bar, click Geoprocessing > Results.
Run a tool
19
Run a tool
20
21
22
9 Click the Check Values button. It validates the cell values in the
batch grid, and in the case of Output Feature Class, populates the
file names with defaults based on the current workspace.
You can also enter the file names one by one, but for filling in a large
number of rows, the Check Values button provides a quick method.
You can make changes to these values by modifying a single cell (for
example, by double-clicking in the cell or right-clicking in the cell and
clicking Open).
The batch tool is now ready to run.
10 Click OK. Once the tool runs, the four output feature classes are added
to the ArcMap table of contents.
23
3 Click OK.
Next, take a look at the following example.
4 Open the Clip tool dialog box.
5 For Input Features, select soils and for Clip Features, select basin.
24
>>> TIP
Although the changes to the
geoprocessing options take
effect immediately, you may
need to retype the name of
the output feature class on
the Clip tool dialog box for
the error icon to disappear.
25
26
As the layers were added, their oval symbols were given a fill color
(blue) because the file name for these data variables is specified. When
the Clip tool was added, its rectangular symbol remained hollow
because the tools parameters have not been specified yet. Hollow symbols indicate that a model is not ready to run. In addition, by its very
nature, the Clip tool produces an Output Feature Class, so this data variable is automatically added to the model, even though it is not pointing
to an output feature class yet.
27
28
19 Click OK to close the tool dialog box. When you click OK to close
the tool dialog box, the tool does not run as it would if you were using
the tool in stand-alone modethat is, outside a model. Instead, with
the tool parameters specified, the appropriate connectors are created in
the model. As a result, the symbol for the Clip tool in the model is now
given a fill color (yellow), and so is the symbol for the output data variable (green). When all parameters are specified and all elements in the
model have a fill color, the model is ready to run.
29
Note: Since you are running the model from within ModelBuilder, the execution of the
model is not recorded in the geoprocessing Results window, but on the model progress
dialog box. If you were to save your model and close it, you could run it as a tool, and then
the tool execution would be recorded in the Results window.
30
2 Click Close to close the Flooding Analysis dialog box. When the
model run is completed, the model elements (other than the input datasets) have a drop shadow to indicate that the tool has been run and the
output datasets have been createdin this case, a shapefile.
31
Next, you can add another step to the model. You may have noticed that
the polygons in the floodzones layer cover the entire study area. This
is how traditional flood maps are organized: polygons cover the entire
study area but are coded as being inside or outside particular flood
zone categories. You next must add a tool to select just the polygons of
interest.
32
8 In ArcToolbox, drag the Select tool from the Extract toolset in the
Analysis toolbox into the model.
33
16 On the ModelBuilder toolbar, first click the Auto Layout button and
then the Full Extent button. Your model should look like the example
in the figure and is now ready to run.
34
that Python code should be typed following the prompt. When a Python script is being
written (which is discussed later in this section), the prompt is no longer used. In many
programming environments, the prompt is referred to as a command prompt, so you may
see either term used in the documentation.
>>> TIP
Instead of using the
prompts, you can also just
keep typing. Even if you
dont use the prompts,
they can be very useful as
reminders of the proper
syntax.
35
3 After your first line of code (import arcpy), press Enter. Pressing
Enter brings up a new prompt at the next line. Remember that Python is
an interpreted language, which means that in the Python window, a single line of code is run as soon as you press Enter.
Now you are ready to run a geoprocessing tool.
4 On the next line of code, enter the following, but do not press Enter
yet:
arcpy.Clip_analysis
This code calls the Clip tool. Python is case sensitive (for the most part),
so be sure to type Clip, not clip. Calling the Clip tool is equivalent to
opening the tool dialog box. The next step is to specify the tools parameters, as if you were filling out the tool dialog box. As you start typing,
the prompts will be helpful to ensure that you use the proper syntax.
When you type an opening left paren [(] after the Clip tool, a drop-down
list appears, containing all the layers from the ArcMap table of contents.
36
6 Press Enter to run the line of code. Similar to when a tool is run from
ArcToolbox, when background processing is enabled a progress bar
appears on the ArcMap status bar to show that the tool is running. Once
the tool execution is complete, a small pop-up notification appears in the
notification area, at the far right of the taskbar. The output feature class is
added to the data frame, and the result is printed in the Python window.
The use of Python code in the Python window is covered in more detail
in chapter 3. For now, it is important to remember that you can run
geoprocessing tools directly from the Python window. Lines of code are
run immediately, and the Python window is highly integrated with the
ArcGIS interface.
In addition to working with Python code in the Python window, you
can write and run code in a Python editor. You will use the PythonWin
editor in the next set of steps to create a simple script.
7 On the taskbar, click the Start button, and then, on the Start
menu, click Programs > Python 2.7 > PythonWin. This brings up the
PythonWin application.
8 On the PythonWin menu bar, click File > New. On the New dialog box,
click Python Script and click OK.
37
9 On the menu bar, click File > Save As and save the script as my_clip.py
to the Results folder for exercise 2 (C:\EsriPress\Python\Data\
Exercise02\Results\my_clip.py). Python script files are simply text
files that have the .py extension. There is no prompt (>>>) in the
script window. Python code in a script is not run until the script is run.
So you can enter multiple lines of code before you run the script.
10 Enter the following code in the my_clip script window:
import arcpy
arcpy.env.workspace = "C:/EsriPress/Python/Data/Exercise02"
arcpy.Clip_analysis("lakes.shp","basin.shp", "results/lakes_myClip.
shp")
Note: This book uses an arrow symbol to indicate long lines of code that appear all on
one line in Python.
Your script window should now look like the example in the figure.
11 On the PythonWin menu bar, click File > Save to save the script.
>>> TIP
After subsequent edits, click the Run button to save the script automatically.
38
The script now runs. Upon execution of the script, it does not initially
appear as if much has happened. Because you are running a stand-alone
script, the output is not automatically added to a data frame in ArcMap.
In fact, ArcMap doesnt need to be open for a script to run.
14 In ArcMap, open the Catalog window, navigate to the Results folder
for exercise 2, and confirm that the lakes_myClip shapefile was
created.
The Python script accomplishes the same task as the Python code in the
Python window: in both places, the Clip tool runs and creates a new
datasetin this case, a shapefile. However, there are a few differences:
The Python window inherits the environments of the geoprocessing framework in ArcMap, but in the stand-alone Python script, the
environments need to be set.
The Python script can run without having any ArcGIS for Desktop
applications open, whereas the Python window is an integral part of
ArcGIS for Desktop applications.
Code in the Python window is run line by line, whereas the standalone Python script is run in its entirety.
These differences between running Python scripts and running code in
the Python window are revisited in later chapters.
39
4 Click Next.
On the next dialog box, you can select the script file that will be
attached to the tool.
5 Click the Browse button and navigate to the Results folder for
exercise 2. Select the my_clip.py script file.
6 Click Next.
The next dialog box allows you to specify tool parameters to be displayed in the tool dialog box. You can skip this for now because the
simple script you are using contains hard-coded parameters, with the
40
10 Click OK to run the tool. When the tool execution is complete, close
the My Clip Tool progress dialog box.
11 In the Catalog window, right-click the Results folder for exercise 2
and click Refresh.
12 Confirm that the lakes_myClip shapefile was created.
Note: Because the script now runs as a tool, it inherits the environment settings and
geoprocessing options of the current ArcMap document. For example, if you were to run
the script tool again without first deleting the lakes_myClip shapefile, the tool would run
fine and overwrite the existing dataset. This is because the Overwrite the outputs of
geoprocessing operations check box was selected under Geoprocessing Options.
As you have just seen, creating a script tool is fairly easy. However,
there is much more to creating robust script tools, including setting
tool parameters to obtain user input, validating input parameters, and
error handling, to name a few. These topics are covered in chapter 13,
after you have had more exposure to Python syntax and writing Python
scripts.
41
42
Dont worry for now about being able to understand everything in the
script. However, you should be able to recognize each of the model elements, including the data variables floodzones and basin, as well as the
Clip and Select tools.
8 Close PythonWin.
9 Close ArcMap. There is no need to save your map document.
In this exercise, you have learned how to run geoprocessing tools and
control how they are run by using tool parameters and environment
settings. You have created a model using the ModelBuilder interface.
You have also run Python code in the Python window as well as running
stand-alone Python scripts and script tools from within an ArcGIS for
Desktop application.
43
Challenge exercise
Challenge 1
Create a new model called Soil Analysis that accomplishes the
following:
1. Clips the soils layer using the basin layer
2. From the clipped version of the soils layer, selects the features that
are Not prime farmland (field FARMLNDCL)
Convert the model to a script called soil.py.
Challenge exercise
44
Exercise 3
3 Drop the Python window on the bottom arrow, so that the window is
at the bottom of the interface.
>>> TIP
Docking the window makes
The Python window itself can be resized, and the divider between the
code section and the Help and syntax panel can be moved. Placement of
the Help and syntax panel can also be controlled.
6 Drag the divider between the code section and the Help and syntax
panel to adjust their sizing the way you like it.
46
47
48
17 Select the text variable and press the Tab key. Then press
Enter to run the code.
It is worthwhile to note that you do not have to use the code
autocompletion prompts. Instead of selecting one of the suggested
terms, you can simply continue typing. You can also turn off the
prompts by right-clicking in the Python window and selecting or clearing
the Show Default Choices option. However, you can benefit from code
49
autocompletion prompts, because using them reduces typos, makes writing code faster, and shows all your options in the drop-down list.
You have already seen how to clear code: right-click in the Python
window and click Clear All. However, you can also continue to run
lines of code, and the window will start to scroll downward if the lines
of code do not fit in the window. Also, clearing the lines of code does
not refresh the interactive Python interpreterrather, the code executed
earlier is still in memory.
18 Right-click in the Python window and click Clear All.
19 At the command prompt, type the following code and press Enter:
>>> print text
Notice that the code printed the correct text, as shown in the figure,
even though the lines of code are no longer visible.
Closing and opening the Python window does not remove the code, nor
does it remove the code from the interactive Python interpreter. However, closing ArcMap removes the code from memory, and you can
never use it again.
20 Close ArcMap and click No if asked to save any changes to the
map document. Start ArcMap again. Open the Python window if
necessary.
21 At the command prompt, type the following code and press Enter:
>>> print text
Notice the result, as shown in the figure.
The variable text is not defined, and therefore the Python window produces an error
message. Code in the Python window is
removed from memory when the ArcGIS
for Desktop application is closed. Later in
this exercise, you will see that there is an
option for saving the Python code.
50
51
6 Select this layer, press the Tab key, and type a closing, right paren [)]:
>>> count = arcpy.GetCount_management("zipcodes")
7 Press Enter to run the line of code. The code runs the Get Count tool.
Once it is finished running, a pop-up notification appears in the notification area, at the far right of the taskbar. Geoprocessing messages also
appear in the Help and syntax panel of the Python window.
Python window.
52
What is shown in the Help and syntax panel is the syntax for the print
statement. When you are just getting started in Python, the wording
may appear a little cryptic.
4 Continue the line of code with the following:
>>> print "GIS
5 With the pointer at the end of the line of code, press F2.
This brings up syntax checking for the current line of code. In this case,
an end-of-line (EOL) error is detected. Pressing F2 effectively prints any
syntax errors that will occur when the line of code is executed.
6 Without fixing the syntax error, press Enter to run the line of code.
Notice that this is the same error as reported using syntax checking.
The F2 key does only syntax checkingother types of errors are discovered only when a tool is actually run.
If you make an error, you may be tempted to correct prior lines of code
that have already been run. However, you can only run code at the current command prompt, so fixing prior lines of code is not an option. To
save on typing, you can copy the line of code, paste it after the current
53
command prompt, and fix the error. Since this is such a common task,
there are built-in shortcuts to make it easier.
7 At the command prompt, press the Up Arrow key to bring up the
previous line of code.
Now you can copy and paste the line of code, fix it, and then run it. The
Up Arrow and Down Arrow keys can be used to scroll up or down to
any previous line of code in the current session.
54
The Python script loads into the Python window. Notice that the lines
of code are preceded by the secondary prompt, meaning that the code
is not run line by line. You can now make changes to the code prior to
running it.
5 Close ArcMap. There is no need to save your map document.
55
Exercise 4
>>> 10 / 3
And the result is 3? What went wrong? The inputs to the calculation
(10 and 3) are both integers, and therefore the result is, by default, also
an integer. This results in rounding. If you want ordinary division, the
solution is to use real numbers or floatsthat is, numbers that are decimals. If either one of the inputs in a division is a float, the result will
also be a float.
Is there a similar upper limit to the size of integers? Yes, ordinary integers cannot be larger than 2147483647 or smaller than -2147483647.
However, if you want larger values, you can use a long integer, commonly referred to as long.
5 Run the following code:
>>> 12345678901
The result is 12345678901L, with the letter L indicating that Python
converted the input value to a long integer.
Basic arithmetic operations such as addition, subtraction, multiplication,
and division are relatively straightforward. Many more operations are
possible, but take a look at just one more for now: the exponentiation,
or power, operator (**).
6 Run the following code:
>>> 2 ** 5
And the result is 32.
Although you are not very likely to use Python directly as a calculator,
the examples here show how Python handles numbers, which will be
useful as you start writing scripts.
57
The code prints Hello World to the next line. This is called a string, as
in a string of characters. Strings are values, just as numbers are.
Python considers single and double quotation marks to be the same
thing, making it possible to use quotation marks within a string.
2 Run the following code:
>>> print 'Let's go!'
The code results in a syntax error because Python does not know how
to distinguish the quotation marks that mark the beginning and end of
the string from the quotation marks that are part of the stringin this
case, in the word Lets. The solution is to mix the type of quotation
marks used, with both single and double quotation marks.
3 Run the following code:
>>> print "Let's go!"
The code prints Let's go! to the next line.
Strings are often used in geoprocessing scripts to indicate path and file
names, so you will see more examples of working with strings throughout the exercise.
58
59
60
Use functions
A function is like a little program you can use to perform a specific
action. Although you can create your own functions, Python has functions already built in, referred to as standard functions.
1 Run the following code:
>>> d = pow (2, 3)
>>> print d
So instead of using the exponentiation operator (**), you can use a
power function called pow. Using a function this way is referred to as
Use functions
61
Use functions
It may not be immediately intuitive as to what many of these functions are used for, although some are straightforward. For example, abs
returns the absolute value of the numeric value.
3 Run the following code:
>>> e = abs(-12.729)
>>> print e
This returns the value of 12.729.
Since it may not be immediately clear how many of these functions
work and what the parameters are, it should be helpful to take a look at
the Help function next.
62
4 First, clean up the Python window by removing all the code so far.
Right-click in the Python section of the window and click Clear All.
5 Make sure the Help and syntax panel is visible by dragging the
divider in place.
6 Type the function type and dont press Enter
yet. Notice that the syntax appears in the adjacent
panel.
You can find similar descriptions in the Python manuals, but having it
right where you are coding in the Python window is convenient. Notice
that a section of the syntax is highlighted. It specifies the parameters
of the function. When you call the function, you need to supply these
parameters for the function to work, although some parameters are
optional.
Next, you can try out this function.
7 Run the following code:
>>> type(123)
The result is <type 'int'>that is, the input value is an integer.
8 Run the following code:
>>> type(1.23)
The result is <type 'float'>that is, the input value is a float, or
floating point.
9 Run the following code:
>>> type("GIS")
The result is <type 'str'>that is, the input value is a string.
Multiple parameters are separated by commas. Optional parameters are
shown between square brackets ([ ]). For example, take a look at the
function range.
Use functions
63
10 In the Python window, type the function range and notice that the
syntax Help appears in the adjacent panel.
Use functions
64
Use methods
Methods are similar to functions. A method is a function that is closely
tied with an objectfor example, a number, a string, or a list. In general,
a method is called as follows:
<object>.<method>(<arguments>)
Calling a method looks just like calling a function, but now the object is
placed before the method, with a dot (.) separating them. Next, take a
look at a simple example.
1 Run the following code:
>>> topic = "Geographic Information Systems"
>>> topic.count("i")
The code returns the value of 2 because that is how often the letter i
occurs in the input string.
A number of different methods are available for strings. Notice that
when you start calling methods by typing a dot after the variable, a list
of methods is provided for you to choose from. The syntax Help is also
context sensitive.
Use methods
65
Next, you can see how to apply the split method to work with paths.
Say, for example, the path to a shapefile is c:\data\part1\final. How
would you obtain just the last part of the path?
3 Run the following code:
>>>
>>>
>>>
>>>
path = "c:/data/part1/final"
pathlist = path.split("/")
lastpath = pathlist[-1]
print lastpath
Use modules
Hundreds of additional functions are stored in modules. Before you can
use a function, you must import its module using the import function.
The functions you used in the preceding sections are part of Pythons
built-in functions and dont need to be imported. One of the most common modules to import is the math module, so start with that one.
Use modules
66
You can learn about each function in the Python manuals, but remember that you can also see the syntax in the Python windows Help and
syntax panel.
3 Type the following code and do not press Enter:
>>> math.floor
Use modules
67
Use modules
68
6 In the documentation
table of contents, under
Indices and tables, click
Global Module Index.
The index provides an
alphabetical list of all the
available modules.
Use modules
69
There are many specialized modules, and in a typical Python script, you
may use several. Try taking a look at just one more. For example, scroll
down to the random module and click the link. Scroll down to the
uniform function and read the description.
Notice that the uniform function has two required parameters, a and b.
You will try this function next in Python.
7 Close the documentation and return to the Python window.
8 Run the following code:
>>> import random
>>> j = random.uniform(0, 100)
>>> print j
The result is a float from 0 to 100.
9 Close ArcMap. There is no need to save your map document.
70
. On the
3 Rearrange the windows so that both the Interactive Window and the
new script window are visible.
Next, you will enter the same code you worked with in the Python
window.
4 In the script window, type the following code:
path = "c:/data/part1/final"
pathlist = path.split("/")
lastpath = pathlist[-1]
print lastpath
Notice that the lines of code in the script window are not preceded by
the prompts (>>>) found in the Interactive Window. Also notice that
nothing is printed when you press Enterthe cursor simply jumps to
the next line as in a text editor. What this means is that in the script
window, the Python code is not actually executed until you run it.
71
6 With your cursor still placed anywhere within the code in the path.
py script window, click the Run button on the PythonWin Standard
toolbar.
>>> TIP
7 This brings up the Run Script dialog box. For now, leave the default
settings and click OK.
72
Note: Indentation is
required in Python. You can
use tabs or spaces to create
indentationthe style you
pick is partly a matter of
preference, but you should
be consistent. Using either
two spaces or four spaces is
most common. By default,
6 Run the script. Running the script may result in a print statement in
the Interactive Window, or nothing at all, depending on your value for p.
73
>>> TIP
Correct indentation is key
else:
print "You lose!"
Notice again the automatic indentation following the else statement.
Now, your code is ready to handle both a true and a false condition.
10 Save and run the script. By using the if-else structure, you account
for all possible outcomes and the script prints a value to the screen
every time you run it, not just when the if statement is True.
One more variant on this is the if-elif-else structure, which youll
use next.
11 Insert a line above the else statement and enter the following code:
elif p == 5:
print "Try again!"
Your code should now look like the example in the figure.
74
12 Run the script a few times until the results include all three conditions. The elif statement is evaluated only if the if statement is
False. You can use elif multiple times, so in principle you could specify an action for every unique possible value of the variable p. Like the
if statement, the elif statement does not need an else statement to
follow. You do, however, need to start this type of branching structure
with an if statementthat is, you cant use elif or else without first
using an if statement. Also notice that all three statements end with
a colon (:) and that there is no end statement as there is in some programming languages.
13 Save your branching.py script and close it.
i = 0
while i <= 10:
print i
i += 1
3 Run the script. The result is a print of the numbers 0 to 10. With each
iteration over the while loop, the value of the variable i is increased by
1. The variable i is referred to as a counter. The while loop keeps going
until the condition becomes falsethat is, when the counter reaches the
value of 11.
The while loop structure uses a syntax similar to the if structure:
the while statement ends with a colon (:), and the next line of code is
indented to create a block.
4 Save and close your whileloop.py script.
Next, you can try a for loop.
5 Create a new Python script and save as forloop.py to the Results
folder for exercise 4.
75
76
15 Run the script. The code determines the largest square below 1,000. A
range of integers is created, starting at 1,000 and counting down to zero
(0). The negative step is used to iterate downward. When the square
root of the integer is identical to the integer of the square root, you have
the solution, and there is no need to continue. The solution is printed,
and the loop ends.
Comment scripts
Well-developed scripts include comments that provide documentation
about the script. Typically, the first few lines of a script consist of comments, but comments also occur throughout a script to explain how the
script works. Comments are not executed when the script is run. In
Python, a comment is preceded by the number sign (#). Any text that
comes after the number sign is ignored during the execution of the script.
Next, you will add some comments that could prove useful in almost
any script you write.
1 In the breakloop.py script, place your pointer at the very beginning
of the code and press Enter. At the top of the script, type the following code:
# Name: <your name>
# Date: <current date>
# Description: This script demonstrates how to break a loop
Your script window should now look like the example in the figure.
Notice that the PythonWin editor recognizes comments and shows them
in green italics.
Comment scripts
77
Adding a comment just before a particular line or block of code can help
other users understand it, as well as serve as a personal reminder about
the codes meaning.
>>> TIP
Adding a line of space in your code is optional and has no effect on running the script.
Typically, lines of space are added for readability. For example, it is common to add a line
before or after comments or to keep lines of related code separate from other sections.
This becomes more important as your scripts get longer.
2 After the if root == int(root) code, enter a few tabs and then
the code:
# This evaluates when the root is an integer
Inserting comments allows you to enter specific comments to explain
very specific parts of your code.
Comment scripts
78
79
80
6 Place your pointer anywhere in the first line of code and click the
Check button
. This checks the syntax of the code without running it. Notice that the cursor is placed at the end of the third line of
code where the syntax error is located, and the status bar at the
bottom of the PythonWin interface reads, Failed to check syntax
error invalid syntax. The Check option provides a quick way to test
the syntax prior to running your script.
7 Now try running the script. In this case, running the script returns the
same result: the cursor is placed at the end of the third line of code, and
the status bar at the bottom indicates a syntax error. For more complicated scripts, it is useful to first identify and remove syntax errors using
the Check option, and then run the script to see if there are other errors.
8 Correct the syntax error by placing a colon (:) at the end of the if
statement:
if p == 6:
9 Now introduce a different error by placing a typo in the randint
function:
p = random.randinr(1, 6)
10 Check the syntax of your script by clicking the Check button.
Clicking Check confirms that there are no syntax errors in your script.
Syntax checking examines the statements and expressions in your code
but does not check for other errors, such as naming a function incorrectly. Only when you run the code will you discover that the function
randinr does not exist.
11 Try running your script. Notice a fairly lengthy error message that is
printed to the Interactive Window. The last three lines read as follows:
File "......\branching.py", line 2, in <module>
p = random.randinr(1,6)
AttributeError: 'module' object has no attribute 'randinr'
The error message provides a clear indication of where the error is
located (line 2 of the code in which you are working with a module) and
what the error is (randinr is not a function of this module).
12 Close PythonWin. There is no need to save the changes to your
script.
81
Challenge exercises
Challenge exercises
Challenge 1
Create a script that examines a string for the occurrence of a particular
letter, as you did previously in this exercise for Geographic Information
Systems. If the letter occurs in the text (for example, the letter Z), the
string Yes should be printed to the Interactive Window. If the letter
does not occur in the text, the string No should be printed.
Challenge 2
Create a script that examines a list of numbers without duplicates (for
example, 2, 8, 64, 16, 32, 4) and determines the second-largest number.
Challenge 3
Create a script that examines a list of numbers (for example, 2, 8, 64,
16, 32, 4, 16, 8) to determine whether it contains duplicates. The script
should print a meaningful result, such as The list provided contains
duplicate values or The list provided does not contain duplicate values.
An optional addition is to remove the duplicates from the list.
Challenge 4
Consider the following list:
mylist = ["Athens", "Barcelona", "Cairo", "Florence", "Helsinki"]
Determine the results of the following:
a)
b)
c)
d)
e)
f)
g)
h)
len(mylist)
mylist[2]
mylist[1:]
mylist[-1]
mylist.index("Cairo")
mylist.pop(1)
mylist.sort(reverse = True)
mylist.append("Berlin")
These operations are all to be performed on the original listthat is, not
as a sequence of operations. Try to determine the answer manually first,
and then check your result by running the code.
82
Part 2
Writing scripts
Exercise 5
Notice that there are five shapefiles in this folder, including point, polyline,
and polygon shapefiles.
3 Drag the parks.shp and zip.shp files to the ArcMap Table Of Contents
window.
5 On the Standard toolbar, click the Python button to open the Python
window.
Use tools
84
Note: Docking the Catalog and Python windows is not required, but it can help to
organize your available desktop space. Typically, it is helpful if the Python window is fairly
wide to make it easier to see longer lines of code.
You are almost ready to run some geoprocessing tools in the Python
window. Before doing so, you must first confirm some geoprocessing
options.
7 On the ArcMap menu bar, click Geoprocessing > Geoprocessing
Options.
Use tools
85
Use tools
86
When you press Enter after the last line of code, the Clip tool is run.
Upon completion, the newly created shapefile parks_Clip.shp is added
as a layer to the data frame, and the result is printed to the Python
window.
Use tools
87
Use tools
Note: Instead of first importing the env class and then setting the current workspace, you
can use a single line of code to do this: arcpy.env.workspace = ....
88
Use tools
14 At the prompt, use the Up Arrow key to bring up the previous line of
code:
>>> arcpy.Buffer_analysis("facilities.shp", "Results/facilities_
buffer.shp", "500 METERS")
15 Next, modify this code to include the optional parameters:
>>> arcpy.Buffer_analysis("facilities.shp", "Results/facilities_
buffer.shp", "500 METERS", "", "", "ALL")
16 Press Enter to run the code. All the buffer features are dissolved into a
single multipart feature, as shown in the figure.
So far, the tool parameters have been hard-codedthat is, the actual
values have been used. Alternatively, you can first assign the value of a
parameter to a variable, and then use the variables in the code that calls
the tool.
17 Run the following code:
>>>
>>>
>>>
>>>
in_features = "bike_routes.shp"
clip_features = "zip.shp"
out_features = "bike_Clip.shp"
xy_tolerance = ""
This creates a variable for each of the tools parameters. Next, you are
ready to run the tool.
89
You can also find the syntax and tool explanation in the Item Description and Help files for each tool.
3 On the ArcMap Standard toolbar, click the Search button
the Search window.
to open
90
4 In the Search window, click Tools to filter the results. In the text box,
type Buffer and press the Search button
.
5 In the list of results, click the definition of the Buffer (Analysis) entry,
starting with Creates buffer polygons .... This opens the Item
Description of the Buffer tool. It contains the same information as in the
ArcGIS for Desktop Help files.
91
6 Scroll down in the Item Description window to see the syntax of the
tool.
92
Finally, code autocompletion prompts can help you write the proper
syntax. For example, when you start typing the parameters for the
Buffer tool, the Python window recognizes which parameters you are
currently working on. In the case of the dissolve_option parameter,
the options are "ALL", "LIST", and "NONE".
93
The Exists function returns a Boolean value. There are several other
ArcPy functions that are not geoprocessing tools, and some of them are
used later in this exercise and other exercises.
One function, in particular, is a useful shortcut for getting the syntax of
ArcPy functions. It is the Usage function, which youll use next.
2 Run the following code:
>>> arcpy.Usage("Clip_analysis")
The result is 'Clip_analysis(in_features, clip_features,
out_feature_class, {cluster_tolerance})\nExtracts
input features that overlay clip features.'
Remember to call geoprocessing tools using a toolbox alias. Calling a
tool only by name will produce an error.
94
You will next use the Define Projection tool to fix it. The syntax of the
Define Projection tool is
DefineProjection_management(in_dataset, coor_system)
95
96
In most cases, you do not have to worry about all these properties, just a
few selected ones.
2 Close ArcGIS for Desktop Help and return to the Python window.
97
environments = arcpy.ListEnvironments()
for environment in environments:
env_setting = eval("env." + environment)
print "{0}: {1}".format(environment, env_setting)
This example code uses the built-in Python eval function. The argument of the function is a Python expression. The eval function
evaluates the expression and returns it as a value. In this case, the function returns a value that represents the particular environment setting.
98
The for loop iterates over the list of environment settings, and they are
printed in the Python window:
newPrecision: SINGLE
autoCommit: 1000
XYResolution: None
XYDomain: None
...
workspace: C:/EsriPress/Python/Data/Exercise05
...
You can also clear specific environment settings or reset all values to
their default.
6 Run the following code:
>>> arcpy.ClearEnvironment("workspace")
>>> print env.workspace
The result is
C:\Documents and Settings\<User>\My Documents\ArcGIS\Default.gdb
7 Run the following code:
>>> arcpy.ResetEnvironments()
>>> print env.outputCoordinateSystem
The result is None.
8 Close ArcMap. There is no need to save your map document.
99
Instead of printing all the messages, you can specify one in particular, as
youll do next.
7 Replace the last line of the code in your my_clip.py script with the
following:
msgCount = arcpy.GetMessageCount()
print arcpy.GetMessage(msgCount-1)
100
8 Save and run your my_clip.py script. This code runs the Clip tool,
determines the number of messages, and returns only the last message:
Succeeded at Wed Feb 01 13:01:41 2012 (Elapsed Time: 1.00 seconds)
Only the messages from the last tool executed are kept by ArcPy. To
obtain messages after multiple tools are run, you can use a result object.
9 Modify your my_clip.py script as follows:
import arcpy
from arcpy import env
env.workspace = "C:/EsriPrss/Python/Data/Exercise05"
env.overwriteOutput = True
newclip = arcpy.Clip_analysis("bike_routes.shp", "parks.shp",
"Results/bike_Clip.shp")
fCount = arcpy.GetCount_management("Results/bike_Clip.shp")
msgCount = newclip.messageCount
print newclip.getMessage(msgCount-1)
10 Save and run your my_clip.py script. The script returns the last message from running the Clip tool, even though another tool was run after
the Clip tool.
101
102
103
Challenge exercises
Challenge exercises
Challenge 1
For each of the following tools, look up the syntax in ArcGIS for
Desktop Help and answer the following questions.
Tools:
Add XY Coordinates
Dissolve
Questions:
What are the required parameters?
What are the optional parameters, and what are their defaults?
Challenge 2
Write a script that runs the Add XY Features tool on the hospitals.shp
feature class.
104
Challenge 3
Write a script that runs the Dissolve tool on the parks.shp feature class
using the PARK_TYPE field as the field for aggregating features. Specify
that multipart features are not allowed.
Challenge 4
Write a script that determines whether the following extensions are available: ArcGIS 3D Analyst, ArcGIS Network Analyst, and ArcGIS Spatial
Analyst. The script should print an informative message with the results,
such as "The following extensions are available: ...".
Challenge exercises
105
Exercise 6
7 Save and run the script. Running the script returns the value of True.
Python, for the most part, is case sensitive, and it applies to strings as
well. One of the exceptions is path and file names, so "cities.shp"
is the same as "CITIES.SHP" and "C:/EsriPress/PYTHON/DATA/
EXERCISE06" is the same as "c:/EsriPress/python/data/
exercise06".
Checking for the existence of data is a function that is commonly used
in stand-alone scripts.
8 Modify the script as follows:
import arcpy
from arcpy import env
env.workspace = "C:/EsriPress/Python/Data/Exercise06"
if arcpy.Exists("cities.shp"):
arcpy.CopyFeatures_management("cities.shp", "results/cities_copy.
shp")
9 Save and run the script. The script determines whether the particular input feature class exists and runs the geoprocessing operation
accordingly.
10 Close PythonWin.
107
2 Drag the five feature classes from the Exercise06 folder into the map
document.
108
109
>>> mylayer.spatialReference.type
The result is u'Geographic'.
>>> mylayer.spatialReference.domain
The result is u'-400 -400 400 400'.
9 Close ArcMap. There is no need to save your map document.
110
111
Running the script prints the name and data type of each feature class
to the Interactive Window, as follows:
Name: amtrak_stations.shp
Data type: ShapeFile
Name: cities.shp
Data type: ShapeFile
Name: counties.shp
Data type: ShapeFile
Name: new_mexico.shp
Data type: ShapeFile
Name: railroads.shp
Data type: ShapeFile
The same approach can be used to work with geoprocessing tools.
6 Save your list.py script as listcopy.py to the Results folder for
exercise 6.
7 Modify the script as follows:
import arcpy
from arcpy import env
env.workspace = "C:/EsriPress/Python/Data/Exercise06"
fclist = arcpy.ListFeatureClasses()
for fc in fclist:
arcpy.CopyFeatures_management(fc, "C:/EsriPress/Python/Data/
Exercise06/Results/" + fc)
8 Save and run the script.
9 In ArcMap, examine the result in the Catalog window. Confirm that
the shapefiles have been copied to the Results folder.
>>> TIP
To see the result in the
Catalog window, right-click
Running the script copies the shapefiles without modifying their names.
In some cases, the names need to be modifiedfor example, when copying shapefiles to a geodatabase. The script you will write next creates
a new empty file geodatabase called NM.gdb and copies the shapefiles
from the workspace to this new geodatabase. However, the name of a
shapefile, by default, includes the file extension .shp, which needs to
be removed. The script therefore uses the basename property of the
feature class rather than the default name for the name of the shapefile.
112
>>> TIP
Some scripts use a statement such as rstrip(".shp") to remove the file extension,
but this can inadvertently remove additional letters from the name. Using the basename
113
Running the script prints a list of the names of the fields in the feature
followed by their type. The result is as follows:
FID OID
Shape Geometry
CITIESX020 Double
FEATURE String
NAME String
POP_RANGE String
POP_2000 Integer
FIPS55 String
COUNTY String
FIPS String
STATE String
STATE_FIPS String
DISPLAY SmallInteger
17 Close PythonWin. There is no need to save the results in the Interactive
Window.
As you have been working through the exercises in this book, you have
probably encountered some unexpected errors. A simple typo can cause
a script not to run properly. Even when all typos are fixed, you may
continue to run into errors. One of the most common error messages is
as follows:
ExecuteError: ERROR 000258: Output C:\<folder>\<file> already exists.
What happens quite often is that you run a script, and then modify it
and try running it again. The script then tries to overwrite existing files
that resulted from the earlier execution of the script, and the script fails.
To overcome these types of errors, you can add the following line to
your script:
env.overwriteOutput = True
This line of code makes it possible for the script to overwrite existing
files. Even with this statement, however, error messages of this type
may continue. If you are running a stand-alone script from PythonWin
and are also using ArcMap or ArcCatalog to examine the results, ArcGIS
for Desktop may have placed a shared lock on the data, preventing it
from being overwritten. This is a common error when working with
geodatabases in particular.
>>> TIP
To overcome error messages
related to a shared lock on
the data, close all ArcGIS for
Desktop applications and
run the script again. When
the script is finished running,
you can open ArcMap or
ArcCatalog to examine the
results.
114
Manipulate lists
Manipulate lists
Lists are widely used in batch geoprocessing. Lists can be manipulated
in a number of ways.
1 Start ArcMap and open the Python window.
2 Run the following code:
>>> arcpy.env.workspace = "C:/EsriPress/Python/Data/Exercise06"
>>> fclist = arcpy.ListFeatureClasses()
>>> print fclist
Running the code prints a list of feature classes as follows:
[u'amtrak_stations.shp', u'cities.shp', u'counties.shp', u'new_mexico.
shp', u'railroads.shp']
Any list in Python can be manipulated using the built-in Python functions and methods. Python lists are indexed starting with the number
zero (0). This makes it possible to obtain specific elements in the list
or to use slicing functions to create smaller lists that contain just the
desired elements. Use indexing next.
3 Run the following code:
>>> fclist[0]
The result is u'amtrak_stations.shp'.
>>> fclist[3]
The result is u'new_mexico.shp'.
>>> fclist[-1]
The result is u'railroads.shp'.
>>> fclist[1:3]
The result is [u'cities.shp', u'counties.shp'].
115
>>> fclist[2:]
The result is as follows:
[u'counties.shp', u'new_mexico.shp', u'railroads.shp']
You can also create a list by typing the elements of the list, which youll
do next.
4 Run the following code:
>>> cities = ["Alameda", "Brazos", "Chimayo", "Dulce"]
The number of features can be determined using the len function,
which will be used next.
5 Run the following code:
>>> len(cities)
The result is 4.
The del statement removes one or more elements from the list.
Because this code does not automatically return the list, a print statement is used to view the current list.
6 Run the following code:
>>> del cities[2]
>>> print cities
The result is ['Alameda', 'Brazos', 'Dulce'].
The sort method can be used to sort the elements in a list, and it can
also be reversed. Try both methods next.
7 Run the following code:
>>> cities.sort(reverse = True)
>>> print cities
The result is ['Dulce', 'Brazos', 'Alameda'].
Manipulate lists
116
>>> cities.sort()
>>> print cities
The result is ['Alameda', 'Brazos', 'Dulce'].
Determining list membership is accomplished using the in operator,
which youll use next.
8 Run the following code:
>>> "Zuni" in cities
The result is False.
The append method can be used to add a new element to the end of the
list, and the insert method makes it possible to add a new element at
a given location, which youll try next.
9 Run the following code:
>>> cities.append("Zuni")
>>> print cities
The result is ['Alameda', 'Brazos', 'Dulce', 'Zuni'].
>>> cities.insert(0,"Espanola")
>>> print cities
The result is as follows:
['Espanola', 'Alameda', 'Brazos', 'Dulce', 'Zuni']
117
This dictionary consists of pairs of cities (the keys) and their corresponding counties. Cities as the keys are unique, whereas the county
values are notthat is, unique cities may be located in the same county.
Notice the syntax, as follows:
The entire dictionary is contained by curly brackets ({ }).
Keys are separated from their values by a colon (:).
Pairs of keys and values are separated from each other by a comma
(,).
Strings are enclosed in double quotation marks (" ").
Once created, the dictionary can be used as a lookup table, which youll
try next.
2 Run the following code:
>>> countylookup["Brazos"]
The result is 'Rio Arriba County'.
Notice that the syntax for dictionaries is similar to working with elements in a list. The name of the dictionary is followed by square
brackets ([ ]), but instead of an index number inside the brackets, one of
the keys is used.
The dictionary is designed to work one way only, which youll see next.
You can only search a dictionary by its keys to get the corresponding
values. You cannot do the reverse and search for a value to get a key.
3 Run the following code:
>>> countylookup["Santa Fe County"]
The code results in an error, as follows:
Runtime error
Traceback (most recent call last):
File "<string>", line 1, in <module>
KeyError: 'Santa Fe County'
In this case, "Santa Fe County" is not one of the keys, and running
the code thus returns an error.
118
Challenge exercises
Challenge exercises
Challenge 1
Write a script that reads all the feature classes in a workspace and prints
the name of each feature class and the geometry type of that feature
class in the following format:
streams is a point feature class
Challenge 2
Write a script that reads all the feature classes in a personal or file
geodatabase and copies only the polygon feature classes to a new file
geodatabase. You can assume there are no feature datasets in the existing data, and the feature classes can keep the same name.
119
Exercise 7
Notice that the script creates a search cursor on the feature class and
uses a for loop to iterate over all the rows of the attribute table.
6 Save and run the script.
The result is a list of the names of all the airports, as follows:
Airport
Airport
Airport
Airport
Airport
Airport
Airport
...
name
name
name
name
name
name
name
=
=
=
=
=
=
=
Hyder
Chignik Lagoon
Koyuk
Kivalina
Ketchikan Harbor
Metlakatla
Waterfall
121
Take another look at the SQL expression used: "TOT_ENP" > 100000.
Field delimiters for shapefiles consist of double quotation marksfor
example, "TOT_ENP"but there are no quotation marks around the
value of 100000 because TOT_ENP is a numeric field. The entire SQL
expression needs to be in quotation marks, because the WHERE clause
in the syntax of the search cursor is a string. This results in the SQL
expression, '"TOT_ENP" > 100000'.
This syntax can create complications. For example, for text fields in SQL
expressions, the values require single quotation marksfor example,
"NAME" = 'Ketchikan'. The statement in the WHERE clause needs to
be in quotation marks, but whether you use double quotation marks
(" ") or single quotation marks (' '), the statement will produce a syntax
error. The solution is to use the escape character (\), which would otherwise cause a syntax error, in front of the quotation marks. In Python,
a backslash within a string is interpreted as an escape character, which
is a signal that the next character is to be given a special interpretation.
So instead of '"NAME" = 'Ketchikan'', the expression becomes
'"NAME" = \'Ketchikan\''.
4 Modify the SQL expression in the script as follows:
cursor = arcpy.da.SearchCursor(fc, ["NAME"], '"FEATURE" =
\'Seaplane Base\'')
5 Save and run the script.
The result is a list of the names of the airports for which the SQL
expression is true, as follows:
Hyder
Ketchikan Harbor
Metlakatla
Waterfall
Kasaan
Hollis
Craig
...
122
123
124
4 Scroll over to the field STATE. Notice that some of the values in this
field are blank.
125
126
127
Note: Although a new record has been added and the attributes can be given values using
the insert cursor, the new record does not have a geometry yet. This is covered in chapter 8.
128
>>> TIP
Validating table and field names does not determine whether the field name already
exists. This requires checking the new name against the names of the existing fields.
129
130
Challenge exercises
>>> TIP
If the feature class does
not appear, you may need
If you keep running the script again, the next output files will be called
buffer1.shp, buffer2.shp, and so on. Using the CreateUniqueName
function can prevent accidentally overwriting files.
Challenge exercises
Challenge 1
Write a script that creates a 15,000-meter buffer around features in the
airports.shp feature class classified as an airport (based on the FEATURE
field) and a 7,500-meter buffer around features classified as a seaplane
base. The results should be two separate feature classes, one for each
airport type.
Challenge 2
Write a script that adds a text field to the roads.shp feature class called
FERRY and populates this field with YES and NO values, depending on
the value of the FEATURE field.
131
Exercise 8
This prints the total length of all the features, followed by the units, to
the Interactive Window, as follows:
256937.409437 Meter
In the print statement, the length is converted to a string because
if it were a number followed by a plus sign (+), it would suggest a
calculation.
Read geometries
In addition to the geometry properties of a feature, a features individual vertices can also be accessed. Youll do that next.
1 In PythonWin, create a new Python script and save as points.py to
the Results folder for exercise 8.
2 Enter the following code:
import arcpy
from arcpy import env
env.workspace = "C:/EsriPress/Python/Data/Exercise08"
fc = "dams.shp"
cursor = arcpy.da.SearchCursor(fc, ["SHAPE@XY"])
for row in cursor:
x, y = row[0]
print("{0}, {1}".format(x, y))
3 Save and run the script.
This prints a pair of x,y coordinates for each point, as follows:
852911.336075 2220578.93538
792026.89767 2310863.76822
784830.427658 2315171.53882
741687.458878 2321601.76549
702480.327773 2340545.89511
623387.057118 2361903.92116
...
Read geometries
133
Read geometries
134
0
1
2
3
4
is
is
is
is
is
single
single
single
single
single
part.
part.
part.
part.
part.
The results are single part for each feature, because each feature consists of a single pointthat is, a dam.
4 Modify the script as follows:
fc = "Hawaii.shp"
135
136
Write geometries
Insert and update cursors can be used to create new features
and update existing features, respectively. Point objects can be
created to set the geometry of these new or updated features.
In the next example, use an insert cursor to create a new polyline feature from a list of coordinates.
1 Start Notepad. Typically, you can get there by clicking the
Start button and then, on the Start menu, click All Programs
> Accessories > Notepad.
2 On the Notepad menu bar, click File > Open and browse to
the Exercise08 folder. Select the coordinates.txt file and
click Open.
The file consists of 34 pairs of x,y coordinates, with each pair
preceded by an ID number and separated by a space. First,
create a new empty polyline feature class, and then use this
list of coordinates to create a new polyline.
3 Close Notepad.
Write geometries
137
Write geometries
The coordinates in this text file will be used to create the vertices for a
polyline. This requires the use of an insert cursor to create new rows
and an array object to contain the point objects.
10 Add the following lines of code:
cursor = arcpy.da.InsertCursor(newfc, ["SHAPE@"])
array = arcpy.Array()
Next, the script needs to read through the text file, parse the text into
separate strings, and iterate over the text file to create a point object for
every line in the text file.
138
When adding the shapefile to the map document, you may get an error
related to the spatial reference because this has not been set. This could
be added to the code using the Create Feature Classes tool or as a separate line of codefor example, by using the Define Projection tool.
Write geometries
139
Challenge exercises
Challenge 1
Write a script that creates a new polygon feature class containing a
single (square) polygon with the following coordinates: (0, 0), (0, 1,000),
(1,000, 0), and (1,000, 1,000).
Challenge 2
Write a script that determines the perimeter (in meters) and area (in
square meters) of each of the individual islands of the Hawaii.shp feature class. Recall that this is a multipart feature class.
Challenge 3
Write a script that creates an envelope polygon feature class for the
Hawaii.shp feature class. There is actually a tool that accomplishes this
called Minimum Bounding Geometry. You can look at the tool to get
some ideas, but your script needs to work directly with the geometry
properties.
Challenge exercises
140
Exercise 9
"Raster
"Raster
"Raster
"Raster
Notice that the band Count property which consists of a number and is
combined using the plus sign (+), needs to be converted into a string for
proper printing.
5 Save and run the script.
142
Running the script prints additional properties that are unique to raster
datasets:
Raster
Raster
Raster
Raster
Raster
Raster
Raster
143
144
>>> TIP
To see the result in the
Catalog window, rightclick a folder (in this case,
the Exercise09 folder) and
click Refresh. This makes
any newly added data files
visible.
145
slope = Slope(elevraster)
goodslope = slope < 20
goodelev = elevraster < 2000
goodfinal = goodslope & goodelev
goodfinal.save("final")
Running this code creates a new raster indicating slope less than 20
degrees and elevation less than 2,000 meters.
146
The result of the code, as shown in the figure, illustrates how map
algebra operators can be used to carry out a series of geoprocessing
operations. All the outputs are temporary raster objects, and only the
final result is saved.
147
148
For discrete data, such as land cover, the RemapValue class is commonly used.
8 In the reclass.py script, replace the three lines of code that pertained
to the reclassification of the elevation raster with the following:
myremap = RemapValue([[41,1], [42,2], [43,3]])
outreclass = Reclassify("landcover.tif", "VALUE", myremap, "NODATA")
outreclass.save("lc_recl")
9 Save and run the script.
149
10 In the Catalog window in ArcMap, confirm that the lc_recl raster has
been created.
Other commonly used classes in raster-based analysis are the neighborhood classes, which youll work with next.
11 Save your reclass.py script as neighborhood.py.
12 In the neighborhood.py script, replace the three lines of code that
pertained to the reclassification of the land cover raster with the
following:
mynbr = NbrCircle(3, "CELL")
outraster = FocalStatistics("landcover.tif", mynbr, "MAJORITY")
outraster.save("lc_nbr")
13 Save and run the script.
150
14 In the Catalog window in ArcMap, confirm that the lc_nbr raster has
been created.
Challenge exercises
Challenge 1
Create a script that determines what areas meet the following
conditions:
Moderate slopebetween 5 and 20 degrees
Southerly aspectbetween 150 and 270 degrees
Forestedland-cover types of 41, 42, or 43
Be sure to use the map algebra expressions of the arcpy.sa module.
Challenge 2
Write a script that copies all the rasters in a workspace to a new file geodatabase. You can use the rasters in the Exercise09 folder as an example.
Challenge exercises
151
Part 3
Carrying out
specialized tasks
Exercise 10
Map scripting
153
7 Close ArcMap.
Running the script prints the names of three data frames to the Interactive
Window:
Facilities
Street Trees
Parks
You can also modify the data frame properties. In the next example,
modify selected properties so they are identical for all data frames in
the map document.
4 Start ArcMap. Open the map document C:\EsriPress\Python\Data\
Exercise10\Austin_TX.mxd.
5 Briefly examine the layers and the properties of each data frame.
Notice that the extent is different for each one, and the coordinate system for the Parks data frame is different from the other two. Next, use
scripting to modify these properties and make them consistent.
6 Close ArcMap.
7 In PythonWin, create a new Python script and save as dfproperties.py
to the Results folder for exercise 10.
8 Enter the following code:
import arcpy
mxd = "C:/EsriPress/Python/Data/Exercise10/Austin_TX.mxd"
mapdoc = arcpy.mapping.MapDocument(mxd)
dataset = "C:/EsriPress/Python/Data/Exercise10/Austin/base.shp"
spatialref = arcpy.Describe(dataset).spatialReference
extent = arcpy.Describe(dataset).extent
for df in arcpy.mapping.ListDataFrames(mapdoc):
df.spatialReference = spatialref
df.panToExtent(extent)
df.scale = 15000
mapdoc.save()
del mapdoc
9 Save and run the script. Running this script sets the spatial reference,
extent, and scale for all the data frames in the map document.
10 Start ArcMap. Open Austin_TX.mxd.
11 Confirm that the data frame properties have been modified.
154
155
156
5 Close ArcMap.
6 In PythonWin, create a new Python script and save as elemproperties.py
to the Results folder for exercise 10.
157
Challenge exercise
Challenge 1
In ArcGIS for Desktop Help, research the AddLayer function of the
ArcPy mapping module and use it to write a script that adds the parks
layer from the Parks data frame in Austin_TX.mxd to the other two data
frames in the same map document.
Challenge exercise
158
Exercise 11
Python Scripting for ArcGIS Exercise 11: Debugging and error handling
This script has a number of syntax errors. You may be able to identify
them directly, but even so, it is useful to see how they can be found.
4 With the cursor placed inside the script, click the Check button. This
displays an error message on the PythonWin status bar. The cursor is
placed at the end of the line where the syntax error occurred: line 5,
character position 17.
>>> TIP
Line numbering can be
made visible in PythonWin
by clicking View > Options
from the menu bar. On the
PythonWin Options dialog
box, click the Editor tab
The error message does not report what the error is, but rather where
it occursyou still must identify the exact nature of the syntax error. In
this case, the error is a missing colon (:) at the end of the line of code.
for fc in fclist:
6 Save and run the script. The script runs but is interrupted, and an error
message appears on the PythonWin status bar, as shown in the figure.
160
Python Scripting for ArcGIS Exercise 11: Debugging and error handling
8 Save and run the script. Again, an error message appears on the
PythonWin status bar, and the details are printed to the Interactive
Window.
Note: For longer error messages, it is best to start reading them from the bottom up. For
example, the last line shows the information about the exact error. Above that, it shows the
line thats in error. And above that, it reports the line number as line 7.
161
Python Scripting for ArcGIS Exercise 11: Debugging and error handling
Take a moment to examine the code. The script creates a list of all
the feature classes in a workspace and copies them to a personal
geodatabase.
2 With your pointer placed inside the script, click the Check button.
There are no syntax errors.
3 Click the Run button.
4 On the Run Script dialog box, under the
Debugging options, click Step-through in
the debugger.
5 Click OK. This brings up the Debugger toolbar, and in the script, a yellow arrow points to the first line of executable code.
162
Python Scripting for ArcGIS Exercise 11: Debugging and error handling
Using the Debugger tools, you can step through the code line by line. If
any errors occur, the error messages will be printed to the Interactive
Window.
6 On the Debugger toolbar, click the Step button. This runs the first
line of code, and the yellow arrow points to the second line of code.
7 Click the Step button again twice. The yellow arrow now points to the
fourth line of code.
8 Click the Step button again. This opens the _base.py module, with the
yellow arrow pointing to line 512 of the script, although the line number may change between different versions of Python. This is one of the
built-in ArcPy scripts. When the workspace is set as part of the environment settings, this module is called. You probably dont want to step
through this module, but let the code run and return to your script so
that you can then continue to step through your own script.
9 On the Debugger toolbar, click the Step Out button twice.
10 Close the _base.py script. This brings you back to your own script,
with the yellow arrow pointing to line 5 of the script.
To avoid opening other modules, use the Step Over button next, instead
of Step. The Step Over button runs the current line of code, and if it
includes any Python modules or functions, they will be run as well, and
the cursor will return to the script itself.
11 Click the Step Over button.
This prints an error message to the Interactive Window, which follows
in part:
AttributeError: 'module' object has no attribute 'ListFeatureclasses'
163
Python Scripting for ArcGIS Exercise 11: Debugging and error handling
fclist = arcpy.ListFeatureClasses()
14 Save the script.
15 Click the Run button.
16 On the Run Script dialog box, under the Debugging options, click
"No debugging". This runs the script, and no more errors are encountered. Successful execution is reported on the PythonWin status bar.
164
Python Scripting for ArcGIS Exercise 11: Debugging and error handling
165
Python Scripting for ArcGIS Exercise 11: Debugging and error handling
Challenge exercises
Challenge exercises
Challenge 1
The following script contains a number of errors. Try to identify all four.
import arcpy
from arcpy import env
env.workspace = "C:/EsriPress/Python/Data/Exercise07"
FC = "airports.shp"
rows = arcpy.SearchCursor(fc)
fields = arcpy.ListFields(fc)
for field in fields:
if fields.name == "NAME"
for row in rows:
print "Name = {0}".format(row.getValue(field.name))
Challenge 2
The following script contains a number of errors. Try to identify all six.
import arcpy
from arcpy import env
env.workspace = "C:/EsriPress/Python/Data\Exercise09"
raster = "landcover.tiff"
desc = arcpy.describe(raster)
x = desc.MeanCellHeight
y = desc.MeanCellWidth
spatialref = desc.spatialReference
units = spatialref.linearUnitName
print "Cells are" + str(x) + " by " + str(y) + " " + units + "."
166
Exercise 12
Python Scripting for ArcGIS Exercise 12: Creating Python functions and classes
168
Python Scripting for ArcGIS Exercise 12: Creating Python functions and classes
8 Save and run the script. Running the script prints the list of field
names to the Interactive Window.
Initially, it does not appear to do anything different from the earlier version of the script that did not define a custom function. However, once
the function is created, it can also be called from another script. You
will do that next.
169
Python Scripting for ArcGIS Exercise 12: Creating Python functions and classes
3 Save and run the script. The result is that the list of field names is
printed twice to the Interactive Window.
170
Python Scripting for ArcGIS Exercise 12: Creating Python functions and classes
5 Indent the last two lines of code. The script should now look like the
example in the figure.
171
Python Scripting for ArcGIS Exercise 12: Creating Python functions and classes
the script is being used to store a custom function to be called only from
other scripts.
10 Modify the list.py script by removing the last three lines of code. The
script should now look like the example in the figure.
172
Python Scripting for ArcGIS Exercise 12: Creating Python functions and classes
This script calculates the property tax assessment based on variables for
land use and the property value.
3 Save the script. The script requires two arguments.
4 Click the Run button. On the Run Script dialog box, enter the arguments as shown in the figure.
5 Click OK. Running the script prints the result of 6250.0 to the
Interactive Window.
To automate this calculation for numerous entries, you would read the
values from a file and iterate over them. Then you would have a few
options to carry out the tax calculation. First, you can place the code
within the iterationthat is, within the for loop or the while loop.
Second, you can create a custom function in a separate script that does
the calculation; when the function is called, the necessary arguments
are passed, and the function returns a value. Third, you can create a
class that contains the calculation as a method.
Next, take a look at the use of a custom function.
6 In PythonWin, create a new Python script and save as tax.py to the
Results folder for exercise 12.
7 Enter the following code:
def taxcalc(landuse, value):
if landuse == "SFR":
rate = 0.05
elif landuse == "MFR":
rate = 0.04
else:
rate = 0.02
assessment = value * rate
return assessment
8 Save your script.
173
Python Scripting for ArcGIS Exercise 12: Creating Python functions and classes
174
Python Scripting for ArcGIS Exercise 12: Creating Python functions and classes
Challenge exercises
Challenge 1
Create a custom function called countstringfields that determines the
number of fields of type string in an input feature class. Create this
function in a separate script (for example, mycount.py) that you call
from another script (for example, callingscript.py). You can use the
streets.shp feature class in the Exercise12 folder.
Challenge 2
You are given a feature class called parcels.shp located in the Exercise12
folder that contains the following fields: FID, Shape, Landuse, and Value.
Modify the parceltax.py script so that it determines the property tax for
each parcel and stores these values in a list. You should use the class
created in the parcelclass.py scriptthe class can remain unchanged.
Print the values of the final list as follows:
FID: <property tax>
Challenge exercises
175
Part 4
Exercise 13
Notice that the names of the input and output feature classes and the
count of random features to be selected are hard-coded into the script.
A few points to note about the script:
The script creates a new empty list, inlist, and this is populated
with the OID (object ID) values of all the features in the input feature class.
The script creates a new empty list, randomlist, and this is populated with 50 OID values randomly selected from inlist.
The output feature class is created by using the OID values in an
SQL expression to select features from the input feature class. The
SQL expression looks a bit complicated but essentially uses the
in operator to query each feature in the input feature class as to
whether its OID value is part of randomlist.
First, run the script to see what the output looks like.
177
178
Next, instead of running the script from PythonWin, create a script tool
so that it can be run from within an ArcGIS for Desktop application.
179
7 On the Add Script dialog box in the second panel, enter the following
information:
a. For Script File, click the Browse button, navigate to the Exercise13
folder, and double-click the script random_sample.py.
b. Leave the check box Show command window when executing
script unchecked. This check box typically appears shaded.
c. Select the check box Run Python script in process.
8 Click Next. On the Add Script dialog box in the third panel, you can add
the script parameters. For now, leave it blank and return to it later.
9 Click Finish. The script tool is now created but has no parameters yet,
because this step was skipped during the initial creation of the tool.
180
11 Double-click the Random Features tool. This opens the dialog box of
the newly created tool. The tool does not have any parameters so the
dialog box is not very informative.
The tool can be executed, howeverthat is, the script can be run from
the new tool dialog box.
12 Leave the tool dialog box open. In the ArcMap table of contents,
right-click the random layer and click Remove.
13 In the Catalog window, browse to the Results folder for exercise 13.
Right-click the feature class random.shp and click Delete.
14 On the Random Features tool dialog box, click OK. This runs the
script, and the progress dialog box appears.
181
Running the script tool this way is possible, but the script still uses the
original hard-coded values. The next step is to add parameters to the
tool and pass them to the script so the user can choose the values.
182
183
184
9 Click OK.
Next, view the parameters on the tool dialog box.
10 In the Catalog window, navigate to the Random Tools toolbox.
Double-click the Random Features tool. This opens the tool dialog box
with its newly created parameters.
11 Click Cancel to close the tool dialog box without running the tool.
Now that the parameters are specified, the script needs to be modified
to read these parameters.
185
186
Next, make changes to the code, save the script, and run the tool to see
if it works correctly.
187
6 Click OK to run the tool. The tool runs, and a new feature class is
created with a random selection of 20 point features.
Challenge exercise
Challenge 1
Make a copy of the random_sample.py script and call it
random_percent.py. Modify the script so that the third parameter
is a percentage of the number of input records as an integer between
1 and 100. Modify the script tool settings so that the input for this
parameter is validated on the tool dialog box.
Challenge exercise
188
Exercise 14
Sharing tools
This folder contains the Random Tools toolbox, which contains the finished script tool, Random Features, but without any documentation.
Although by default you can see the toolbox and script tool, Python
scripts are not, by default, visible in ArcCatalog. Instead, you can use
Windows Explorer (My Computer) to view and manage your scripts.
However, you can modify the ArcCatalog options to make Python
scripts visible. Youll do that next.
2 On the menu bar, click Customize >
ArcCatalog Options.
3 On the ArcCatalog Options dialog box,
click the File Types tab.
Unless you have previously added file
types here, this panel should be empty.
4 Click New Type.
5 On the File Type dialog box, click Import File Type From Registry.
6 On the Registered File Types dialog box, browse to the Python File
entry (PY).
7 Click the Python File entry (PY) and click OK. This brings up the File
Type dialog boxthis time populated with the details of Python script
files, including the icon.
190
>>> TIP
When Windows 7 or Vista is used, depending on the system configuration, only a very limited
number of registered file types may be shown. If there is no entry called Python File, the File
extension box on the File Type dialog box can be filled in manually. When the File Type dialog
box is filled in manually, an icon is not automatically created. An icon can be chosen by
clicking the Change Icon button and browsing to an appropriate file. For a typical installation
of Python 2.7, the icon can be found at C:\Python27\ArcGIS10.1\DLLs\py.ico.
8 On the File Type dialog box, click OK. Python script files now appear
on the File Types tab.
191
13 Move the Random Tools toolbox file into the Random root folder and
move the random_sample.py script into the Scripts folder.
Moving the script relative to the .tbx file means that the relative path
needs to be updated, which youll do next.
14 Right-click the Random Features script tool and click Properties.
15 On the Random Features Properties dialog box, click the Source tab.
16 For Script File, browse to C:\EsriPress\Python\Data\Exercise14\
Random\Scripts\random_sample.py.
17 Click OK.
With the folder structure created, additional files can be added, such as
sample data or documentation, which youll add next.
192
4 In the Item Description panel, for Summary, type: Creates a new feature class based on a random selection of features in the input feature
class.
5 For Usage, type the following as a bullet list:
The input feature class can be points, polylines, or polygons.
The output features consist of the same geometry type as the input
features.
The number of features can range from 0 to the number of features in
the input feature class.
6 For Syntax, click Input Features > Dialog Explanation and type: Input
feature class from which features are to be selected. Can be points, polylines, or polygons.
193
7 For Syntax, click Output Features > Dialog Explanation and type:
Output feature class containing the randomly selected features.
8 For Syntax, click Number of Features > Dialog Explanation and type:
The number of features to be selected. Needs to be specified as an integer between 0 and the number of features in the input feature class.
Much more information can be entered on the Description page, but
these basic elements illustrate the concept.
9 On the panel toolbar, click the Save button
The tool description can now be viewed on the tool dialog box, as youll
see next.
10 In the Catalog tree, double-click the Random Features script tool.
11 On the Random Features dialog box, click the Show Help button.
The summary description appears in the Help panel to the right.
12 On the tool dialog box, click the Input Features parameter to see
the description in the Help panel. Also, try the other two parameters, Output Features and Number of Features, to see their Help
messages.
194
13 Click the Tool Help button to open the Help file in a web browser.
14 Scroll down and see your inputs to the tool Description page. Notice
that some items may need to be filled in later: Code Samples, Tags,
and Credits.
15 Close the browser window.
195
Challenge exercise
Challenge 1
Go to the Geoprocessing section of the online ArcGIS for Desktop
Resource Center at http://resources.ArcGIS.com/content/geoprocessing .
Click the Model and Script Tool Gallery and browse through some of
the recent postings. Preview the details of a tool that looks interesting to
you. Once you confirm that the tool uses Python, download the toolif
it does not, keep looking until you find a tool that does.
Once the tool is downloaded and extracted, review the contents of the
files and answer the following questions:
How is (are) the tool(s) made available to users? As a .tbx file with
one or more .py files? As stand-alone .py files?
What is the folder structure, if any, of the files that make up the tool?
What type of documentation is provided, separate from the script
itself? Is there a Help page on the tool dialog box?
Open the .py files in PythonWin and review the scripts documentation.
See if you can recognize the following elements of a script:
Importing modules, such as ArcPy and others
Receiving parameters from the tool dialog box, such as
GetParameterAsText
Error-handling techniques, such as the try-except statement
Custom functions, such as def
Message handling, such as the AddMessage and AddWarning
functions
Challenge exercise
196
Solutions
Exercise 1
No challenge exercises.
Exercise 2
Challenge 1
The ModelBuilder result is shown in the figure.
198
Exercise 3
No challenge exercises.
Exercise 4
Challenge 1
mytext = "Geographic Information Systems"
result = mytext.find("Z")
if result == -1:
print "No"
else:
print "Yes"
Challenge 2
mylist = [2, 8, 64, 16, 32, 4]
mylist.sort()
mylist[-2]
Challenge 3
mylist = [2, 8, 64, 16, 32, 4, 16, 8]
for number in mylist:
count = mylist.count(number)
if count <> 1:
result = "The list provided contains duplicate values."
break
else:
result = "The list provided does not contain duplicate
values."
print result
Optional addition to remove duplicates from the list:
mylist = [2, 8, 64, 16, 32, 4, 8, 16]
mylist.sort()
for number in mylist:
count = mylist.count(number)
if count <> 1:
mylist.remove(number)
print mylist
Challenge 4
a) 5
b) 'Cairo'
c) ['Barcelona', 'Cairo', 'Florence', 'Helsinki']
d) 'Helsinki'
e) 2
f) 'Barcelona'; new list: ['Athens', 'Cairo', 'Florence', 'Helsinki']
g) No result prints; new list: ['Helsinki', 'Florence', 'Cairo', 'Barcelona',
'Athens']
h) No result prints; new list: ['Athens', 'Barcelona', 'Cairo', 'Florence',
'Helsinki', 'Berlin']
199
Exercise 5
Challenge 1
For Add XY Coordinates tool:
Syntax: AddXY_management(in_features)
Required parameter: in_features (feature layer, geometry type
point)
Optional parameters: none
For Dissolve tool:
Syntax: Dissolve_management(in_features, out_feature_class,
{dissolve_field}, {statistics_fields}, {multi_part}, {unsplit_lines})
Required parameters:
in_features (feature layer)
out_feature_class (feature class)
Optional parameters:
dissolve_field (field or fields; default: no fields selected)
statistics_fields (field or fields; default: no fields selected)
multi_part (Boolean value; default: multipart features allowed)
unsplit_lines (Boolean value; default: lines dissolved)
Challenge 2
import arcpy
from arcpy import env
env.workspace = "C:/Data"
arcpy.AddXY_management("hospitals.shp")
Challenge 3
import arcpy
from arcpy import env
env.workspace = "C:/Data"
arcpy.Dissolve_management("parks.shp", "parks_dissolved.shp",
"PARK_TYPE",
"", "FALSE")
200
Challenge 4
import arcpy
default = "no extensions are available"
if arcpy.CheckExtension("3D") == "Available":
ext_3D = "3D Analyst "
else:
ext_3D = ""
if arcpy.CheckExtension("Network") == "Available":
ext_network = "Network Analyst "
else:
ext_network = ""
if arcpy.CheckExtension("Spatial") == "Available":
ext_spatial = "Spatial Analyst "
else:
ext_spatial = ""
print "The following extensions are available: " + ext_3D + ext_
spatial + ext_network + default
Exercise 6
Challenge 1
import arcpy
from arcpy import env
env.workspace = "C:/Data"
fc_list = arcpy.ListFeatureClasses()
for fc in fc_list:
desc = arcpy.Describe(fc)
print "{0} is a {1} feature class".format(desc.basename,
desc.shapeType)
Challenge 2
import arcpy
from arcpy import env
env.workspace = "C:/Data/study.mdb"
fc_list = arcpy.ListFeatureClasses()
arcpy.CreateFileGDB_management("C:/Data", "newstudy.gdb")
for fc in fc_list:
desc = arcpy.Describe(fc)
if desc.shapeType == "Polygon":
arcpy.Copy_management (fc, "C:/Data/newstudy.gdb/" + fc)
201
Exercise 7
Challenge 1
import arcpy
from arcpy import env
env.workspace = "C:/EsriPress/Python/Data/Exercise07"
sql1 = " \"FEATURE\" = 'Airport'"
sql2 = " \"FEATURE\" = 'Seaplane Base'"
arcpy.Select_analysis ("airports.shp", "Results/airports_final.shp",
sql1)
arcpy.Select_analysis ("airports.shp", "Results/seaports.shp", sql2)
arcpy.Buffer_analysis("Results/airports_final.shp", "Results/aiports_
buffers.shp", "15000 METERS")
arcpy.Buffer_analysis("Results/seaports.shp", "Results/seaports_
buffers.shp", "7500 METERS")
Challenge 2
import arcpy
from arcpy import env
env.workspace = "C:/EsriPress/Python/Data/Exercise07"
fc = "roads.shp"
arcpy.AddField_management(fc, "FERRY", "TEXT", "", "", 20)
cursor = arcpy.da.UpdateCursor(fc, ["FEATURE", "FERRY"])
for row in cursor:
if row[0] == "Ferry Crossing":
row[1] = "YES"
else:
row[1]= "NO"
cursor.updateRow(row)
202
Exercise 8
Challenge 1
import arcpy
from arcpy import env
env.workspace = "C:/Data"
fc = "newpoly2.shp"
arcpy.CreateFeatureclass_management("C:/Data", fc, "Polygon")
cursor = arcpy.da.InsertCursor(fc, ["SHAPE@"])
array = arcpy.Array()
coordlist =[[0, 0], [0, 1000], [1000, 1000], [1000, 0]]
for x, y in coordlist:
point = arcpy.Point(x,y)
array.append(point)
polygon = arcpy.Polygon(array)
cursor.insertRow([polygon])
del cursor
Challenge 2
import arcpy
from arcpy import env
env.workspace = "C:/EsriPress/Python/Data/Exercise08"
fc = "Hawaii.shp"
newfc = "Results/Hawaii_single.shp"
arcpy.MultipartToSinglepart_management(fc, newfc)
spatialref = arcpy.Describe(newfc).spatialReference
unit = spatialref.linearUnitName
cursor = arcpy.da.SearchCursor(newfc, ["SHAPE@"])
for row in cursor:
print ("{0} square {1}".format(row[0].area, unit))
203
Challenge 3
import arcpy
from arcpy import env
env.workspace = "C:/EsriPress/Python/Data/Exercise08"
fc = "Hawaii.shp"
newfc = "envelope8.shp"
desc = arcpy.Describe(fc)
spatialref = desc.spatialReference
extent = desc.extent
arcpy.CreateFeatureclass_management("C:/EsriPress/Python/Data/
Exercise08", newfc, "Polygon", "", "", "", spatialref)
cursor = arcpy.da.InsertCursor(newfc, ["SHAPE@"])
array = arcpy.Array()
array.append(extent.upperLeft)
array.append(extent.upperRight)
array.append(extent.lowerRight)
array.append(extent.lowerLeft)
polygon = arcpy.Polygon(array)
cursor.insertRow([polygon])
del cursor
Exercise 9
Challenge 1
import arcpy
from arcpy import env
from arcpy.sa import *
env.workspace = "C:/EsriPress/Python/Data/Exercise09"
if arcpy.CheckExtension("Spatial") == "Available":
arcpy.CheckOutExtension("Spatial")
elev = arcpy.Raster("elevation")
lc = arcpy.Raster("landcover.tif")
slope = Slope(elev)
aspect = Aspect(elev)
goodslope = ((slope > 5) & (slope < 20))
goodaspect = ((aspect > 150) & (aspect < 270))
goodland = ((lc == 41) | (lc == 42) | (lc ==43))
outraster = (goodslope & goodaspect & goodland)
outraster.save("C:/EsriPress/Python/Data/Exercise09/Results/final")
arcpy.CheckInExtension("Spatial")
204
Challenge 2
import arcpy
from arcpy import env
out_path = "C:/EsriPress/Python/Data/Exercise09"
env.workspace = out_path
rasterlist = arcpy.ListRasters()
arcpy.CreatePersonalGDB_management(out_path + "/Results", "myrasters.
gdb")
for raster in rasterlist:
desc = arcpy.Describe(raster)
rname = desc.baseName
outraster = out_path + "/Results/myrasters.gdb/" + rname
arcpy.CopyRaster_management(raster, outraster)
Exercise 10
Challenge 1
import arcpy
from arcpy import env
env.workspace = "C:/EsriPress/Python/Data/Exercise10"
mxd = arcpy.mapping.MapDocument("C:/EsriPress/Python/Data/Exercise10/
Austin_TX.mxd")
df = arcpy.mapping.ListDataFrames(mxd, "Parks")[0]
lyr = arcpy.mapping.ListLayers(mxd, "parks", df)[0]
dflist = arcpy.mapping.ListDataFrames(mxd)
for dframe in dflist:
if dframe.name <> "Parks":
arcpy.mapping.AddLayer(dframe, lyr)
mxd.save()
del mxd
205
Exercise 11
Challenge 1
The four coding errors are highlighted in yellow as follows:
import arcpy
from arcpy import env
env.workspace = "C:/EsriPress/Python/Data/Exercise07"
FC = "airports.shp"
rows = arcpy.SearchCursor(fc)
fields = arcpy.ListFields(fc)
for field in fields:
if fields.name == "NAME":
for row in rows:
____print "Name = {0}".format(row.getValue(field.name))
Challenge 2
The six coding errors are highlighted in yellow as follows:
import arcpy
from arcpy import env
env.workspace = "C:/EsriPress/Python/Data\Exercise09"
raster = "landcover.tiff"
desc = arcpy.describe(raster)
x = desc.MeanCellHeight
y = desc.MeanCellWidth
spatialref = desc.spatialReference
units = spatialref.linearUnitName
print "Cells are" + str(x) + " by " + str(y) + " " + units + "."
206
Exercise 12
Challenge 1
For callingscript.py:
import arcpy
import mycount
table = "C:/EsriPress/Python/Data/Exercise12/streets.shp"
print mycount.countstringfields(table)
For mycount.py:
import arcpy
import os
def countstringfields(table):
fields = arcpy.ListFields(table)
i = 0
for field in fields:
if field.type == "String":
i += 1
return i
Challenge 2
For parcelclass.py:
import arcpy
import parcelclass
from arcpy import env
env.workspace = "C:/EsriPress/Python/Data/Exercise12"
fc = "parcels.shp"
cursor = arcpy.da.SearchCursor(fc, ["FID", "Landuse", "Value"])
for row in cursor:
myparcel = parcelclass.Parcel(row[1], row[2])
mytax = myparcel.assessment()
print "{0}: {1}".format(row[0], mytax)
207
Exercise 13
Challenge 1
import arcpy
import random
from arcpy import env
env.overwriteOutput = True
inputfc = arcpy.GetParameterAsText(0)
outputfc = arcpy.GetParameterAsText(1)
percent = int(arcpy.GetParameterAsText(2))
desc = arcpy.Describe(inputfc)
input_count = int(arcpy.GetCount_management(inputfc)[0])
outcount = int(round(input_count * percent * 0.01))
inlist = []
randomlist = []
fldname = desc.OIDFieldName
rows = arcpy.SearchCursor(inputfc)
row = rows.next()
while row:
id = row.getValue(fldname)
inlist.append(id)
row = rows.next()
while len(randomlist) < outcount:
selitem = random.choice(inlist)
randomlist.append(selitem)
inlist.remove(selitem)
length = len(str(randomlist))
sqlexp = '"' + fldname + '"' + " in " + "(" + str(randomlist)
[1:length - 1] + ")"
arcpy.MakeFeatureLayer_management(inputfc, "selection", sqlexp)
arcpy.CopyFeatures_management("selection", outputfc)
In the script tool, the parameter Number of Features is replaced by
Percent of Features of type Integer with a range filter from 0 to 100.
Exercise 14
Challenge 1
Results will vary with the tool selected.
208