PYTH 4.2 Sep10 Workbook
PYTH 4.2 Sep10 Workbook
Using Python®
Copyright © 2004-2008, 2010 Esri
The information contained in this document is the exclusive property of Esri. This work is protected under United States copyright law and
other international copyright treaties and conventions. No part of this work may be reproduced or transmitted in any form or by any means,
electronic or mechanical, including photocopying and recording, or by any information storage or retrieval system, except as expressly
permitted in writing by Esri. All requests should be sent to Attention: Contracts and Legal Services Manager, Esri, 380 New York Street,
Redlands, CA 92373-8100 USA.
EXPORT NOTICE: Use of these Materials is subject to U.S. export control laws and regulations including the U.S. Department of Commerce
Export Administration Regulations (EAR). Diversion of these Materials contrary to U.S. law is prohibited.
@esri.com, 3D Analyst, ACORN, Address Coder, ADF, AML, ArcAtlas, ArcCAD, ArcCatalog, ArcCOGO, ArcData, ArcDoc, ArcEdit,
ArcEditor, ArcEurope, ArcExplorer, ArcExpress, ArcGIS, ArcGlobe, ArcGrid, ArcIMS, ARC/INFO, ArcInfo, ArcInfo Librarian, ArcLessons,
ArcLocation, ArcLogistics, ArcMap, ArcNetwork, ArcNews, ArcObjects, ArcOpen, ArcPad, ArcPlot, ArcPress, ArcReader, ArcScan,
ArcScene, ArcSchool, ArcScripts, ArcSDE, ArcSdl, ArcSketch, ArcStorm, ArcSurvey, ArcTIN, ArcToolbox, ArcTools, ArcUSA, ArcUser,
ArcView, ArcVoyager, ArcWatch, ArcWeb, ArcWorld, ArcXML, Atlas GIS, AtlasWare, Avenue, BAO, Business Analyst, Business Analyst
Online, BusinessMAP, CommunityInfo, Database Integrator, DBI Kit, EDN, Esri, Esri—Team GIS, Esri—The GIS Company, Esri—The GIS
People, Esri—The GIS Software Leader, FormEdit, GeoCollector, Geographic Design System, Geography Matters, Geography Network, GIS
by Esri, GIS Day, GIS for Everyone, GISData Server, JTX, MapIt, Maplex, MapObjects, MapStudio, ModelBuilder, MOLE, MPS—Atlas,
PLTS, Rent-a-Tech, SDE, SML, Sourcebook·America, Spatial Database Engine, StreetMap, Tapestry, the ARC/INFO logo, the ArcGIS logo,
the ArcGIS Explorer logo, the ArcPad logo, the Esri globe logo, the Esri Press logo, the GIS Day logo, the MapIt logo, The Geographic
Advantage, The Geographic Approach, The World's Leading Desktop GIS, Water Writes, www.esri.com, www.geographynetwork.com,
www.gis.com, www.gisday.com, and Your Personal Geographic Information System are trademarks, registered trademarks, or service marks
of Esri in the United States, the European Community, or certain other jurisdictions.
Other companies and products mentioned herein may be trademarks or registered trademarks of their respective trademark owners.
Introduction
Introduction............................................................................................................. vi
Course goals .......................................................................................................... vi
Using the course workbook ................................................................................... vii
Additional resources .............................................................................................. vii
Installing the course data ...................................................................................... vii
1 What is Python?
Lesson introduction ............................................................................................. 1-1
Integrated Development Environments (IDEs) .................................................... 1-2
Python terminology.............................................................................................. 1-4
Python data types................................................................................................ 1-5
Built-in functions .................................................................................................. 1-6
Python modules................................................................................................... 1-7
Statements .......................................................................................................... 1-8
Tips.................................................................................................................... 1-10
Exercise 1: Learn the basics of Python ............................................................. 1-11
Create a script and comment code ............................................................. 1-11
Work with variables..................................................................................... 1-14
Explore built-in functions............................................................................. 1-19
Work with modules...................................................................................... 1-19
Make decisions ........................................................................................... 1-22
Work with loops........................................................................................... 1-23
Challenge: Work with functions................................................................... 1-26
Python resources .............................................................................................. 1-27
Lesson review ................................................................................................... 1-28
Python reference ............................................................................................... 1-29
Answers to Lesson 1 questions .................................................................. 1-32
Challenge solution: Work with functions ..................................................... 1-34
Exercise solution ........................................................................................ 1-35
i
Run a Python script in the Python window................................................. 2-11
Challenge: Run the Clip tool in the Python window ................................... 2-12
Lesson review .................................................................................................. 2-13
Creating the geoprocessor ............................................................................... 2-14
Answers to Lesson 2 questions ................................................................. 2-16
Challenge solution: Run the Clip tool in the Python window...................... 2-18
Exercise solution ....................................................................................... 2-19
ii
Exercise 5: Working with lists ............................................................................ 5-10
List all the file geodatabases in a folder...................................................... 5-10
List all the fields in a feature class .............................................................. 5-11
Delete raster datasets in a folder ................................................................ 5-11
Lesson review ................................................................................................... 5-13
Answers to Lesson 5 questions .................................................................. 5-14
Exercise solution ........................................................................................ 5-18
iii
Exercise 7B: Buffer multiple feature classes .................................................... 7-21
Replace hard-coded values with dynamic values ...................................... 7-21
Attach a script with arguments to a tool in ArcToolbox .............................. 7-21
Run the BufferMultipleFC script tool .......................................................... 7-24
Lesson review .................................................................................................. 7-25
Answers to Lesson 7 questions ................................................................. 7-26
Exercise solution: 7A ................................................................................. 7-27
Exercise solution: 7B ................................................................................. 7-28
iv
10 Manipulating data schema and working with subsets of
data
Lesson introduction ........................................................................................... 10-1
Feature layer and table view ............................................................................. 10-3
Tools that create and manage feature layers and table views .......................... 10-4
Workflow problem.............................................................................................. 10-5
Creating a FeatureLayer object ......................................................................... 10-6
Using the FieldInfo object .................................................................................. 10-7
Using field delimiters in a SQL query ................................................................ 10-8
Exercise 10: Working with subsets of data...................................................... 10-10
Create a subset of features....................................................................... 10-10
Perform analysis on FeatureLayer............................................................ 10-11
Lesson review ................................................................................................. 10-13
Answers to Lesson 10 questions .............................................................. 10-14
Exercise solution ...................................................................................... 10-16
Appendixes
Appendix A: Esri data license agreement ........................................................... A-1
v
Introduction
Course goals
The course workbook is an integral part of your learning experience. During class, you will use
the workbook to complete activities and exercises that reinforce specific tasks and skills. After
class, the workbook is your personal reference to review activities or work through exercises
again to reinforce what you've learned.
Essential elements include:
▪ Lessons—learning objectives at the beginning of each lesson to help you find the
information you're looking for
▪ Guided activities—interactive activities to reinforce key topics
▪ Exercises—step-by-step instructions for accomplishing essential tasks and building skills
▪ Review—questions and answers that reinforce key concepts
▪ Appendixes—your guide to additional resources
▪ CD—data necessary for completing the course exercises
Additional resources
To complete the workbook exercises for this course, you must install the necessary data. The
data is stored on a disc and will be copied to your hard drive by an automated install program.
Remove the disc from the back of your course workbook and place it in the disk drive.
Note: If you need to install the course data to a different location, browse to and
select the folder, then click OK. Note the location of the folder so that
you can easily access the data in the exercises.
▪ Click Next.
▪ Click Finish when the installation is complete.
Remove the disc and return it to its sleeve in your workbook.
Introduction
This lesson will introduce you to Python, a free open-source, cross-platform programming
language. Programs written in the Python scripting language are called scripts, which are not
compiled but rather interpreted when you run them. Python is automatically installed when you
install ArcGIS. You will use PythonWin 2.6 to enter, debug, and test your code. PythonWin is
not installed by ArcGIS, but is a free download available on the Internet.
All scripting languages have a standard set of functionality. For example, every scripting
language has the ability to comment code, execute loops, concatenate strings, run
decision-making statements, and execute a set of built-in functions. The main differences
between scripting languages are the syntax and the type of built-in functionality.
Learning objectives
1-1
What is Python?
In course exercises, you will use PythonWin, which has already been installed for you.
PythonWin IDLE
Python IDE and GUI Framework for Windows Python's Integrated DeveLopment
Environment
Download from Automatically installed with ArcGIS
http://sourceforge.net/projects/pywin32
Microsoft Windows only Most platforms that support Python
▪ Windows-based UI ▪ Menu-driven UI
with menus and toolbars ▪ Many windows
▪ Windows contained within a single
application
What are variables and why would you use them in a Python
script?
Notes
Python terminology
Throughout this lesson, you will explore Python data types, Python built-in functions, modules
available to import into your scripts, as well as how to write conditional statements and work
with Python lists and dictionaries.
Built-in functions
Examples:
fc = "Railroads.shp"
len(fc)
---> 13
yCoord = 1811884.623964
round(yCoord)
---> 1811885.0
Python modules
To import a module into your script, use the import statement, followed by the name of the
module. After the module is imported, you can call any function from the module by prefixing
the name of the module to the name of the function. The syntax is:
<modulename>.<functionname>
Examples:
import math
math.sqrt(64) ---> 8.0
math.pow(10,2) ---> 100.0
import string
string.split("-155.3 -43.5") ---> ['-155.3', '-43.5']
string.upper("c:\\student") ---> 'C:\\STUDENT'
import os.path
os.path.basename("C:\\Student\\Streets.shp") ---> 'Streets.shp'
os.path.dirname("C:\\Student\\Streets.shp") ---> 'C:\\Student'
Statements
Note: When testing to see if a particular condition it true, always use two equal signs
(==), not one. Two equal signs are used to test for a condition, whereas one
equal sign is used to assign a value to a variable. For example:
x = 1 # assignment
y = 8 + 2 # assignment
if x == 6: # testing a condition
▪ List loops iterate over each value in a list. In other words, the loop will execute once for
each value in the list. At the end of each while or for statement, a colon is required. If
you forget the colon, you will get a syntax error. To finish a loop, dedent the code.
Tips
Python is mostly case sensitive.
▪ All of Python's functions and statements are case sensitive. You can tell if you have
written a function or statement correctly in a Python script because it will turn blue. If a
function or statement is not colored blue, then you have made an error, either in the
spelling or in the case sensitivity.
▪ Variable names are also case sensitive. This is unlike many other programming and
scripting languages. (Be careful when programming in Python if you are used to
programming in VBScript or in Visual Studio .NET.) A special naming rule in Python
applies to variables. Any variable name you use in Python must start with a character or
underscore. Variable names cannot start with a number.
Note: At ArcGIS 10, all the geoprocessing properties and methods are case
sensitive. When migrating your existing scripts from 9.3 to 10, make sure
that you correct your geoprocessing properties or methods.
▪ Pathnames are not case sensitive. This means that any pathname can contain mixed
case letters.
In this exercise, you will become familiar with the Python scripting language, specifically
comments, variables, built-in functions, modules, concatenation, decision-making statements,
and loops. You will also become familiar with Python language best practices.
In this exercise, you will:
▪ Create a script and comment code
▪ Work with variables
▪ Work with built-in functions
▪ Work with modules
▪ Make decisions with statements
▪ Work with loops
Start PythonWin from the shortcut on your desktop or from the taskbar.
PythonWin is one of the integrated development environments (IDE) that you can use for
writing Python scripts. When you open PythonWin, it opens with the Interactive Window. The
Interactive Window has many purposes:
1. It provides a quick way to execute and test individual lines of code without saving
that code.
2. It outputs error messages from scripts.
3. It shows the output from print statements.
Resize the Interactive Window so that it covers the bottom half of the application.
Note: You can run Pychecker against your Python script to look for a range of Python
syntax errors and formatting. You can use Grep to scan a directory and find words
within all types of files within a directory. For example: find "mdb" in all .py files.
Click OK.
Currently, you have two windows within your application: the Interactive Window and the
Script1 window. You can write lines of code in either window. However, the code that you
write in the Interactive Window cannot be saved directly to a Python script. For this reason,
most of your code will be written in a script window.
Resize the Script1 window so that it covers the top half of the application.
Click within the Script1 window, then click File > Save As.
In the Save As dialog box, navigate to the C:\Student\PYTH\Exercise01 folder, and save
the file as BasicsOfPython.py.
The first lines of code in any script should always be comments—lines of unexecutable code that
are used to document a script. Include information about the author, date, and purpose of the
script. You should also include comments throughout the code to explain individual lines or
blocks of code. Properly commented code is essential to making a script comprehensible and
readable to other programmers.
In Python, any line of code preceded by one or more pound signs (#) is interpreted as a
comment. When you run a script, Python ignores all commented lines of code and only
executes the uncommented lines of code.
In the BasicsOfPython.py window, below the comments, type the following code:
a = 5
print a
On the Standard toolbar, click the Check button to check your code syntax.
The status bar reports that the script was checked successfully.
The value that is stored in a is printed to the Interactive Window. The print statement always
sends output to the Interactive Window.
In the BasicsOfPython.py window, after the print a statement, type the following code:
b = 5 + 6
print b
Run the script. (Click the Run button. In the Run Script dialog box, click OK.)
The values that are stored in a and b are printed to the Interactive Window. The value of b
holds the number 11, which is the sum of 5 + 6.
Variables can store string values. String values must be enclosed in single or double quotes.
Note: When using the Interactive Window, there are several shortcut keys available.
▪ Recall previous command: Ctrl+Up
▪ Recall next command: Ctrl+Down
▪ Auto-complete variable name: Ctrl+Space
In the BasicsOfPython.py window, after the print b statement, type the following code:
c = "Hello"
print c
The word Hello is the last line printed to the Interactive Window.
In addition to storing one value inside a variable, you can store multiple values inside a variable.
These are known as lists. You can extract a single value (or a subset of values) from a list based
on the index position.
In the BasicsOfPython.py window, after the print c statement, type the following code:
The last three lines of output in the Interactive Window are Jack, Lisa, and Lisa.
▪ d[0] returns Jack, which is the first value in the list (lists are zero-based).
▪ d[2] returns Lisa, which is the third value in the list.
▪ d[-1] returns Lisa, which is the first value from the right.
You can also use the same indexing functionality on an individual string. The indexing
functionality is not limited to lists.
In the BasicsOfPython.py window, after the print d[-1] statement, type the following
code:
e = "Railroads.shp"
print e[3]
print e[-2]
print e[0:-4]
The last three lines of output to the Interactive Window are l, h, and Railroads.
▪ e[3] returns l, which is the fourth character in the string (strings are zero-based).
▪ e[-2] returns h, which is the second character from the right.
▪ e[0:-4] returns Railroads, which includes all characters excluding the last four.
In the next step, you will learn about Python's built-in functions and how those functions are
used with variables. Before moving on to functions, you will comment out the existing lines of
code.
Two gray pound signs (##) are placed in front of each line of code.
Verify that the last print statement is commented out. If you did not press Enter after the
last line of code, the line will not be commented out.
When writing scripts, there will be times when you want to combine two strings together. You
can do this using the plus sign (+).
In the BasicsOfPython.py window, after the print e[0:9] statement, type the following
code:
f = "Streets"
g = ".shp"
print f + g
The two string values are concatenated together and Streets.shp is printed to the Interactive
Window.
At times, you might need to concatenate a string value with a non-string value.
In the BasicsOfPython.py window, after the print f + g statement, type the following
code:
h = 1
print f + h + g
An error is returned because you are trying to concatenate string values with non-string values.
You can use the str built-in function to change a non-string value to a string value. You will
learn more about Python built-in functions in the next exercise step.
h = 1
print f + str(h) + g
The three string values are concatenated together and Streets1.shp is printed to the Interactive
Window.
In the BasicsOfPython.py window, at the end of the script, type the following code:
i = round(3.4)
print i
You can access the list of built-in functions using the dir(__builtins__) statement.
In the BasicsOfPython.py window, after the print i statement, type the following
code—note that there are two underscores before the word builtins and two underscores
after it:
print dir(__builtins__)
______________________________________________________________________________
There are several dozen built-in functions that are available with Python. You can use any of
these functions in a script. Python, however, is not limited to this list of built-in functions. In the
next step, you will learn how to access additional functions.
Note: Most code that you type in a script can be typed into the Interactive Window as
well. The main difference is the code that you type in the Interactive Window is
not saved to a script. Therefore, once you exit PythonWin, you will no longer
have access to that code.
The first module that you will import is the math module.
In the Interactive Window, verify that you have the >>> prompt. If not, press Enter.
Do not type the three arrows (>>>). When you see the three arrows in
documentation, it indicates that the code should be written in the Interactive
Window.
Press Enter.
This statement provides access to all the functions in the math module, but does not list them.
You will use the dir statement in the math module to list the functions.
In the Interactive Window, type the following code and press Enter.
>>> dir(math)
______________________________________________________________________________
______________________________________________________________________________
You can learn the definition and syntax of a function by using the __doc__ statement. Note that
there are two underscores before and two underscores after the word doc.
In the Interactive Window, type the following code and press Enter.
Note: The print statement is not required in the Interactive Window, but the output is
formatted better if you use the print statement.
The Interactive Window shows the syntax and the definition of the sqrt function. You can use
this information to properly code the sqrt function.
▪ Syntax: sqrt(x).
▪ Definition: Return the square root of x.
In the Interactive Window, type the following code and press Enter.
>>> math.sqrt(64)
Notice that you need to prefix non-built-in functions with the name of the module. This makes
your code more readable because you will always know where a function is coming from.
Using the skills that you just learned, import the random module and obtain a list of all the
functions in the random module.
______________________________________________________________________________
The help statement can also display the syntax and definition for a function.
In the Interactive Window, type the following code and press Enter.
>>> help(random.choice)
______________________________________________________________________________
______________________________________________________________________________
In the Interactive Window, type the following code and press Enter.
In the Interactive Window, press Ctrl+Up Arrow to recall the command, then press Enter.
Repeat a few times to see that the value returned from the list is truly random.
The math and random modules are just two of the modules that are available to import. There
are dozens of other modules available.
To view a list of the modules, in the Interactive Window, type help ('modules') and
press Enter.
A listing of all available modules prints to the Interactive Window (after a brief delay).
x = 5
if x < 5:
print "The number is less than 5"
elif x > 5:
print "The number is greater than 5"
else:
print "The number is equal to 5"
Currently, the value of x is equal to 5; therefore, the else statement gets executed and the
Interactive Window reports, The number is equal to 5.
If you have time, change the value of x to a number greater than 5, then a number less
than 5, and rerun the script.
In the BasicsOfPython.py window, at the end of the script, type the following code:
y = 1
while y < 10:
print y
y = y + 1
These lines of code represent a while loop. In a while loop, the loop continues to execute while
the condition is true. Each line of code is described below:
▪ Line 1: y is initially assigned a value of 1.
▪ Line 2: As long as y is less than 10, enter the loop.
▪ Line 3: Print the value of y to the Interactive Window.
▪ Line 4: Add the value of 1 to y and go back to the top of the loop (Line 2).
The while loop will continue to execute until y is greater than or equal to 10. Once y reaches a
value of 10, the loop will terminate.
______________________________________________________________________________
The second type of loop is the list loop. A list loop will loop over each value in a list until the list
is empty.
In the BasicsOfPython.py window, at the end of the script, type the following code:
These three lines of code represent a list loop. In this example, the list loop will run three times,
once for each value in the list.
The third type of loop is the counted loop. A counted loop will loop over a range of values.
In the BasicsOfPython.py window, at the end of the script, type the following code:
These two lines of code represent a counted loop. In this example, the loop will run four times,
once for each value in the range. The last number in the range is never included.
Write all the code for this step in the Interactive Window.
Print the following string, minus the last four characters, to the Interactive Window:
"Parcels.shp"
Python resources
Python offers a lot of functionality of which only a small part is covered in this course. If you
want to learn more about Python syntax and functionality, you can purchase one of the many
books available on the market or go to Python's Web site to find helpful resources.
Books
▪ Learning Python (4th edition), by Mark Lutz and David Ascher
▪ Learn to Program Using Python, by Alan Gauld
▪ Python in a Nutshell (2nd edition), by Alex Martelli
▪ Python Cookbook (2nd Edition), by Alex Martelli, Anne Martelli Ravenscraft, and David
Ascher
Web sites
▪ http://www.python.org
Tutorials, documentation, and forums
▪ http://diveintopython.org
Dive Into Python, by Mark Pilgrim
▪ http://openbookproject.net/thinkCSpy/
How to Think Like A Computer Scientist: Learning with Python (2nd Edition) , by Jeffrey
Elkins, Allen B. Downey, and Chris Meyers
▪ http://sourceforge.net/projects/pywin32/
PythonWin installation
▪ http://code.activestate.com/recipes/langs/python
Extensive collection of Python scripts (very few GIS scripts)
Lesson review
1. Is PythonWin installed by ArcGIS?
______________________________________________________________________________
______________________________________________________________________________
______________________________________________________________________________
4. Write a line of Python code that prints the built-in functions to the Interactive Window.
______________________________________________________________________________
if x = 5:
print "x is equal to 5"
elif x > 5
print "x is greater than 5"
else:
print "x is not equal to or greater than 5'
Python reference
Variables A variable is simply a name that represents a value. To create the
variable, assign a value to the name. An example might be x = 3. To
evaluate the value, simply refer to the name as in print x.
Numbers The number data type can store numbers and expressions. Numbers are
distinguished from strings because they are not surrounded by quotes.
Numbers can represent something as simple as a single digit to
something as complex as the return value of a mathematical expression.
Python In Python, the most basic form of a data structure is a sequence. Each
Lists element of the sequence is assigned a number (or index). The first data
element startes with 0, the second with 1, the third with 2, and so forth.
To determine the number of elements in the Python list, you can use the
Python List method count, or the Python built-in function len().
Tuples Tuples store sequences just like Python Lists, but they are not
changeable. Just like Python Lists, the elements in the tuple are
accessed by their index number.
Line continuation
Lines of code can become very long. To make your code more readable, continue long lines of
code onto another line. This will ensure that the user does not need to scroll through the code.
There are a number of line continuation characters in Python.
▪ The backslash (\) character at the end of a line will continue a line onto the next line.
▪ Enclosing values in parentheses, brackets, or braces will also continue a line onto the
next line.
Either way will work, but it is more common today for Python programmers to use parentheses,
brackets, or braces than the backslash. As long as you use parentheses, brackets, braces, or a
backslash, Python recognizes the line continuation and automatically indents your code when
you press Enter.
Yes
Yes.
No.
Yes.
choice(self, seq)
Numbers 1 to 9. The number 10 does not get printed because the loop only executes if the
value is less than 10.
Lesson review
No.
4. Write a line of Python code that prints the built-in functions to the Interactive Window.
dir(__builtins__)
if x = 5:
print "x is equal to 5"
elif x > 5
print "x is greater than 5"
else:
print "x is not equal to or greater than 5'
▪ Line 1 is missing an equal sign (=). In Python, a single equal sign means to assign
a value and a double equal sign means to evaluate the value.
▪ Line 3 is missing a colon (:). All conditional statements must end with a colon.
▪ The last line is using a single quotation mark (') at the end of the line instead of a
double quotation mark ("). Quotation marks must be balanced: if you use a single
quotation mark at the start of a text string, it must end with a single quotation
mark. The same logic applies for double quotation marks.
Solution:
if x == 5:
print "x is equal to 5"
elif x > 5:
print "x is greater than 5"
else:
print "x is not equal to or greater than 5"
>>> "Parcels.shp"[0:-4]
Exercise solution
BasicsOfPython.py
# Name: ESRI
# Date:
# Purpose: This script is an exercise to learn the Python scripting language.
a = 5
print a
b = 5 + 6
print b
c = "Hello"
print c
e = "Railroads.shp"
print e[3]
print e[-2]
print e[0:-4]
f = "Streets"
g = ".shp"
print f + g
h = 1
print f + str(h) + g
i = round(3.4)
print i
print dir(__builtins__)
x = 5
if x < 5:
print "The number is less than 5"
elif x > 5:
print "The number is greater than 5"
else:
print "The number is equal to 5"
y = 1
while y < 10:
print y
y = y + 1
Introduction
Working with geoprocessing functionality has come a long way since it was first introduced.
Geoprocessing functionality could be accessed by running tools in ArcToolbox, creating a
model in ModelBuilder, or running the geoprocessing tool by its name in a Command Line
window.
ArcPy is a site package that provides useful and productive ways to perform geographic data
analysis, data conversion, data management, and map automation with Python.
In this lesson, you will explore the ArcPy site package in the ArcGIS Desktop Help and access
ArcPy in both ArcGIS Desktop and in PythonWin.
Learning objectives
2-1
ArcPy: What's the big deal?
Key terms
▪ ArcPy
▪ ArcPy modules
▪ ArcPy classes
▪ ArcPy functions
Note: For definitions, go to the ArcGIS Desktop Help, and navigate to:
▪ Professional Library >
▪ Geoprocessing >
▪ The ArcPy site package >
▪ Essential ArcPy vocabulary
When you work with an ArcPy class, the object that you
create will exist only in memory and cease to exist once the
script completes or when you close the Python IDE. The
advantage is that intermediate storage on disk is not needed
in order to use the object.
ArcPy classes can create geometry objects such as Points, Polylines, and Polygons, as well as
SpatialReference or Extent objects. These objects can be used to create and update features, or
to represent feature classes, tables, fields, or spatial references. Other types of objects that can be
created from ArcPy classes include Field, Raster, Row, and FeatureSet objects, just to name a
few.
ArcPy functions support certain geoprocessing workflows. For example, you can:
▪ List data for automating processing of datasets.
▪ Describe data properties for decision-making in a script.
▪ Step through features in a feature class or rows in a table using a cursor data access
object for reporting, updating field values, or creating new data.
▪ Make sure the Catalog window in ArcMap reflects the latest changes to data.
▪ Update layers in your map document.
▪ Set and/or receive parameter values in your scripts.
▪ Provide reports about the ArcGIS Desktop installation on a computer.
▪ Add messages to the progress dialog and update the progress dialog status bar.
▪ Add your custom toolbars to the Python session.
1. If your geodatabase was moved to a new folder or drive location and you had several map
documents that pointed to the older location, which ArcPy module should you import in
your script so that you can repair the map documents?
______________________________________________________________________________
2. How can you import all of the ArcPy sub-modules into your script?
______________________________________________________________________________
import arcpy.ga as GA
GA.CrossValidation(...)
Additional notes
arcpy.mapping Contains functions and classes for working with map documents (MXD)
to fix and repair layers and workspaces, report contents of the MXD,
print out map series for map book creation, and export the maps to
many graphic formats including PDF, TIFF, JPEG, AI, and PNG.
arcpy.sa Provides a shortcut to the Spatial Analyst tools, functions, operators
and classes for working with rasters and surfaces. An advantage to
using this module is that the geoprocessing tool, function, or class can
be more easily referenced in the script by a shortened name. For
example:
In this exercise, you will access ArcPy in both the ArcMap Python window and in a script that
you will write in PythonWin.
The Corvallis school district has approached you to create a new crime analysis feature class.
The requirements are that the schools are to be buffered by 500 meters, but the buffers must not
extend outside the city boundary line by more than 1500 meters.
You decide that the best approach is to create the school buffers using the ArcMap Python
window first, then create a new script in PythonWin and test run it. When your new script runs
successfully in PythonWin, you will run the same script in the ArcMap Python window and
view the results. Finally, you will access the Clip_analysis tool from the Python window to clip
the school buffers against the buffered boundary line for the final output.
In this exercise, you will:
▪ Run the Buffer tool in the Python window
▪ Create a script in PythonWin
▪ Run the script in the Python window
Open ArcMap. (From the Start menu, choose All Programs > ArcGIS > ArcMap.)
In the ArcMap - Getting Started dialog box, navigate to Existing Maps > Browse for
more.
Open the ArcGIS Desktop Help (Click Start > All Programs > ArcGIS > ArcGIS Desktop
Help > ArcGIS Desktop 10 Help).
In the ArcGIS 10 Help window, on the Contents tab, expand the following:
▪ Professional Library >
▪ Geoprocessing >
▪ Executing tools >
▪ Executing tools using the Python window >
▪ Using the Python window
Select Executing tools in the Python window and review the contents of this topic to answer
the following questions.
1. Where can you find the tool name for a geoprocessing tool that you want to run in the
Python window?
______________________________________________________________________________
______________________________________________________________________________
______________________________________________________________________________
3. In the Python window, how do you get help for a geoprocessing tool?
______________________________________________________________________________
______________________________________________________________________________
arcpy.env.workspace = "C:/Student/PYTH/Database/Corvallis.gdb"
arcpy.Buffer_analysis(
Note: You do not need to import the ArcPy site package when using the Python
window.
Notice that the syntax for the Buffer tool displays in the Help and Syntax panel of the Python
window.
Using the displayed syntax, enter the required parameters to buffer 500 meters from the
Schools and create the SchoolsBuff500 feature class.
Notice that by default the newly created output dataset is added to ArcMap as a layer.
Leave ArcMap open. You will return to the Python window in a later step.
If necessary, start PythonWin from the shortcut on your desktop or from the taskbar.
In PythonWin, create a new Python Script and save the file as Buffer_boundary.py in the
C:\Student\PYTH\Exercise02 folder.
In the Run Script dialog box, click the OK button to run your script.
If you encounter any errors, ask your instructor for help or refer to the ArcGIS Desktop Help.
Note: When applicable, the workbook includes exercise solutions at the end of the
lesson.
Close PythonWin.
It is always a good idea to verify that your script has not only completed successfully but that it
also ran correctly.
Next, you will verify that the new Boundary polygon feature class has been created.
In ArcMap:
▪ Click the Add Data button.
▪ Browse to C:\Student\PYTH\Database\Corvallis.gdb.
▪ Add theBoundaryLine and Boundary1500 feature classes to the map.
▪ Verify that the Buffer tool created Boundary1500 correctly.
One of the geoprocessing options that you can set is the option to overwrite the output of
geoprocessing operations. You will set this option now.
In the Geoprocessing Options dialog box, check the option to Overwrite the outputs of
geoprocessing operations, then click OK.
In the Python window, press the Enter key to run the script.
4. If you encountered errors or if the features in the new Boundary1500 layer are not correct,
what steps should you perform?
______________________________________________________________________________
______________________________________________________________________________
Finally, you will clip the school buffers to the Boundary1500 polygon.
In the Python window, use the Clip analysis tool to clip the SchoolsBuff500 layer by the
Boundary1500 layer to produce the new ClippedSchoolsBuffer layer.
Lesson review
1. How can you access geoprocessing functionality in Python scripts?
______________________________________________________________________________
______________________________________________________________________________
______________________________________________________________________________
______________________________________________________________________________
______________________________________________________________________________
______________________________________________________________________________
______________________________________________________________________________
______________________________________________________________________________
______________________________________________________________________________
______________________________________________________________________________
______________________________________________________________________________
______________________________________________________________________________
______________________________________________________________________________
ArcGIS 10
ArcGIS 10 introduces the ArcPy site package for Python, which integrates Python into the
Desktop world. You can choose to run your geoprocessing scripts in any of these ways:
▪ In a Python Integrated Development Environment application
▪ Schedule the script to run at a certain time
▪ From ArcToolbox as a tool
▪ From a menu in ArcGIS Desktop
▪ As a background process in ArcGIS Desktop
▪ In the Python window
ArcGIS 10 supports backward compatibility with scripts that use the arcgisscripting
module.
You can create the geoprocessor object using the ArcGIS 9.2 or 9.3 create method, but not all
ArcPy functionality will be available in your script.
1. If your geodatabase was moved to a new folder or drive location and you had several map
documents that pointed to the older location, which ArcPy module should you import in
your script so that you can repair the map documents?
The arcpy.mapping module contains the functions to fix and repair layers in your map
documents.
2. How can you import all of the ArcPy sub-modules into your script?
import arcpy
1. Where can you find the tool name for a geoprocessing tool that you want to run in the
Python window?
In the tool properties, which you can access in the Catalog or ArcToolbox windows.
Unlike the tool label (which displays in ArcToolbox and at the top of the tool's dialog
box), the tool name does not contain spaces.
Use an empty set of quotation marks, a pound sign within quotation marks, or specify
the parameter name.
3. In the Python window, how do you get help for a geoprocessing tool?
Type the geoprocessing tool name at the Python window prompt followed by an open
parenthesis. The tool usage and help documentation will display in the Python window
Help and Syntax panel.
4. If you encountered errors or if the features in the new Boundary1500 layer are not correct,
what steps should you perform?
Close ArcMap to remove any locks on the data, open the script in PythonWin and check
for syntax or logic errors, and verify that the parameters used for the Buffer tool are
correct.
Lesson review
The ArcPy site package provides Python access for all geoprocessing tools, including
extensions, as well as a wide variety of useful functions and classes for working with and
interrogating GIS data.
The arcpy.mapping module can be used to open and manipulate ArcMap map documents
(.mxd) and layer files (.lyr). Scripts that use arcpy.mapping can open map documents
(.mxd) and layers, query and alter the contents, and then print, export, or save the
modified document.
ArcPy provides access to geoprocessing tools as well as additional functions, classes, and
modules that allow you to create simple or complex workflows quickly and easily.
Scripts written using ArcPy benefit from being able to access and work with any Python
module.
Exercise solution
Buffer_boundary.py
# Name: <your name>
# Date: <current date>
# Purpose: This script will buffer the Boundary
# polyline feature class by 1500 meters.
Introduction
In this lesson, you will examine several steps in debugging code using PythonWin. Knowing
how PythonWin finds syntax errors in a script can help quickly locate the problem.
Learning objectives
3-1
Debugging your scripts
import arcpy
arcpy.env.Workspace = "C:\Student\\PYTH\\Database\\SanDiego.mdb"
inFC = "Railroads"
distance = 500
For fc in listFc:
print fc
Print len(lstFc)
Import math
z = 25
y = 6
x = math.sqrt(z)
if x = y:
print "x and y are the same"
elif x > y:
print "x is greater than y"
else
print "x is less than y"
When writing scripts, it is almost impossible to have a script that never produces an error. This
is especially true if it interacts with an end user.
In this exercise, you will debug a script that:
▪ Prints the arcpy.env.workspace directory name
▪ Creates a list of rasters in the directory
▪ Loops through the list, printing each raster name and format type
The status bar reports that there is invalid syntax in the script, and the cursor is placed on the
following line of code:
lstRAS = arcpy.ListRasters(*)
______________________________________________________________________________
There is another syntax error in the script. The cursor is placed within the following line of
code:
if dscRAS.format = "GRID":
______________________________________________________________________________
There is another syntax error in the script. The cursor is placed within the following line of
code:
Print "The " + ras + " raster is stored in the ESRI GRID format"
______________________________________________________________________________
There is another syntax error in the code. The cursor is placed at the end of the following line of
code:
else
______________________________________________________________________________
Congratulations! The PythonWin status bar reports that the script was checked successfully.
You are now ready to run your script.
A traceback error is printed to the Interactive Window. The NameError indicates that the name
'os' is not defined. This error occurs when a variable name is used before a value is assigned, or
when a module is not imported before being referenced.
______________________________________________________________________________
Below the import arcpy statement, add a line of code that imports the os module.
The PythonWin Interactive Window still displays the error text. You can clean up this window
by right-clicking within it and choosing Select All, then right-clicking again and choosing Cut.
Click the Check button. Fix any errors that may be found.
Your debugged script should now complete without error. Each raster name and format type
prints to the Interactive Window.
Lesson review
1. Where do you debug your code?
______________________________________________________________________________
______________________________________________________________________________
______________________________________________________________________________
______________________________________________________________________________
3. List the main reason why you might receive a NameError: name 'os' is not defined in the
Interactive Window.
______________________________________________________________________________
______________________________________________________________________________
Since the code is evaluating the value of dscRAS.format, a double-equal sign must be
used.
Yes, the line of code that prints the directory path uses os.path.dirname
Lesson review
3. List the main reason why you might receive a NameError: name 'os' is not defined in the
Interactive Window.
Exercise solution
MyListAndPrintRasters.py
# Author: ESRI
# Date: <Today>
# Purpose: This script prints the names of the rasters located in the
# Tahoe/All folder and lists the raster format type
# Import the ArcPy site package and set the workspace location
import arcpy
import os
arcpy.env.workspace = r"C:\Student\PYTH\Database\Tahoe\All"
# Iterate through the Python List, printing the raster name and
# if the raster is stored inthe GRID format.
# You will learn more about the ArcPy Describe function in Lesson04
for ras in lstRas:
dscRAS = arcpy.Describe(ras)
if dscRAS.format == "GRID":
print "The " + ras + " raster is stored in the ESRI GRID format"
else:
print "The " + ras + " raster is not stored in the ESRI GRID format"
Introduction
The Describe function on the ArcPy site package is a function that returns a Describe object
that provides descriptive information about the type of data being described. The types of data
that can be described include geodatabases, geodatabase tables, feature classes, rasters,
shapefiles, folders, coverages, layer files, etc.
Each property of the object that the Describe function returns can be used to control the flow of
a script. For example, a script might ask a user for a feature class to buffer. Depending on the
ShapeType of the feature class, the parameter values for the Buffer tool will differ.
Learning objectives
4-1
Using Describe objects
Describing a raster
Raster properties
import arcpy
arcpy.env.workspace = "C:/Student/PYTH/Database/SanDiego.gdb"
dscFC = arcpy.Describe("Climate")
2. Describe a dataset.
import arcpy
arcpy.env.workspace = "C:/Student/PYTH/Database/Redlands.gdb"
dscDS = arcpy.Describe("Census")
if dscDS.____________ == "FeatureDataset":
3. Describe a raster.
import arcpy
arcpy.env.workspace = "C:/Student/PYTH/Database/Tahoe"
dscRS = arcpy.Describe("Emer/erelev")
if dscRS._______ == "GRID":
...
if dscRS.datasetType == "______________":...
if dscRS.________________ == "JPEG2000":
...
import arcpy
import arcpy
The Describe function returns a Describe object that contains properties of the input data. These
properties can be used to report some descriptive information of the input data, logically control
the flow of a script or provide a parameter to a geoprocessing tool.
In this exercise, you will:
▪ Describe a feature class
▪ Describe a raster dataset
1. What ArcGIS Desktop Help topic might you use to help write this script?
______________________________________________________________________________
______________________________________________________________________________
The shape type and extent of the Railroad feature class are printed to the Interactive Window.
2. What is the geometry shape type for the Railroad feature class?
______________________________________________________________________________
For reference, here is the syntax for the Raster Clip tool:
One way to get the clipping extent rectangle (a required parameter) is to refer to the raster
dataset properties in ArcCatalog, and manually type in the minimum and maximum x,y values
for your rectangle parameter.
Another way is to use a Describe object in your script. In this step, you will use a Describe
object to return the extent of a raster dataset. Then you will use the returned extent to clip
another raster dataset.
Now you will verify the extent values that the Describe function returned for the erelev raster
dataset.
3. Scroll down to the Extent properties and record the values below.
4. Is the extent returned from the Describe function the same as the extent that you obtained
from ArcCatalog?
______________________________________________________________________________
Now you are ready to run the Clip tool in your script.
Clip the \All\arowner raster with the extent of \Emer\erelev to create a new
\Emer\erowner raster.
▪ For the Raster Clip tool's second argument, use the extent of erelev.
(Hint: Remember that the Describe function returns an object. The Clip tool will need
the string representation of the extent property.)
Lesson review
1. When describing a feature class, what are some of the properties returned?
______________________________________________________________________________
______________________________________________________________________________
______________________________________________________________________________
______________________________________________________________________________
______________________________________________________________________________
______________________________________________________________________________
______________________________________________________________________________
3. Give an example of how you could use a Describe object in a geoprocessing tool.
______________________________________________________________________________
______________________________________________________________________________
import arcpy
arcpy.env.workspace = "C:/Student/PYTH/Database/SanDiego.gdb"
dscFC = arcpy.Describe("Climate")
2. Describe a dataset.
import arcpy
arcpy.env.workspace = "C:/Student/PYTH/Database/Redlands.gdb"
dscDS = arcpy.Describe("Census")
3. Describe a raster.
import arcpy
arcpy.env.workspace = "C:/Student/PYTH/Database/Tahoe"
dscRS = arcpy.Describe("Emer/erelev")
1. What ArcGIS Desktop Help topic might you use to help write this script?
Professional Library > Geoprocessing > The ArcPy site package > Functions >
Describing data > Describe properties > FeatureClass properties
2. What is the geometry shape type for the Railroad feature class?
Polyline
3. Scroll down to the Extent properties and record the values below.
4. Is the extent returned from the Describe function the same as the extent that you obtained
from ArcCatalog?
Yes.
Lesson review
1. When describing a feature class, what are some of the properties returned?
▪ featureType
▪ shapeType
▪ shapeFieldName
▪ hasM
▪ hasZ
An Extent object, which has properties for X-Min, Y-Min, X-Max, Y-Max, as well as
other properties.
3. Give an example of how you could use a Describe object in a geoprocessing tool.
Exercise solution
DescribeFC.py
# Author: ESRI
# Date:
# Purpose: To describe a feature class.
# Print the shape type and extent of the Railroad feature class
# to the Interactive Window.
print dscFC.shapeType
print dscFC.extent
ClipRDExtent.py
# Author: ESRI
# Date:
# Purpose: Clip a raster by the extent of another raster
# using a describe object
Introduction
One of the primary tasks in scripting is automating the processing of data with a list of data. The
ArcPy site package has many list functions that are built to return Python lists for different types
of data. In this lesson, you will explore these ArcPy list functions.
Learning objectives
5-1
Automating scripts with Python lists
Click the List function links to help you answer the following questions:
1. The ListFeatureClasses function returns a Python list. What data type is the returned
value? What do the values contain?
______________________________________________________________________________
2. The ListFields function returns a Python list that contains Field objects. What are some
of the field object properties that you can access?
______________________________________________________________________________
______________________________________________________________________________
3. Referring to the code sample for the ListFields function, how do you iterate through the
Python list that the function returns?
______________________________________________________________________________
1. List datasets.
import arcpy
arcpy.env.workspace = "C:\\Student\\PYTH\\Database\\World.gdb"
dsList = arcpy.List_________("*")
for ds in _______:
______ ds
import arcpy
arcpy.env.workspace = "C:/Student/PYTH/Database/SanDiego.gdb"
fldList = arcpy.ListFields("_________________")
print ____._____
print ____._____
import arcpy
arcpy.env.workspace = "C:/Student/PYTH/Database/Tahoe/Emer"
rdList = arcpy.____________("___")
arcpy.BuildPyramids_management(____)
Workflow
1. Import arcpy
2. Set the current workspace as the location to look for the feature classes
3. Call the ListFeatureClasses function and assign the return to a variable
4. Iterate with a for loop through the variable, which contains a Python list
5. For each item in the list, print the item to the Interactive Window
arcpy.env.workspace = "C:\\Student\\PYTH\\Database\\SanDiego.gdb"
fcList = arcpy.ListFeatureClasses("*")
for fc in fcList:
print "Feature class name: " + fc
import arcpy, os
startLocation = r"C:\Student\PYTH"
foundFCS = {}
The ArcPy List functions can catalog available data filtered by the type of data for which you
are looking and return a Python list of values. These values may be items such as feature class
names, raster names, shapefiles in a folder, or a list of fields in a table.
In this exercise, you will write scripts to:
▪ List the geodatabases in a folder
▪ List all the fields in a feature class
▪ Delete all the specified rasters in a folder
Note: Refer to the Listing Data help topic to determine the correct List function to use.
(ArcGIS Desktop Help > Professional Library > Geoprocessing > Geoprocessing
with Python > Working with sets of data in Python)
Iterate through the returned Python list and print the name of each geodatabase to the
Interactive Window.
______________________________________________________________________________
Iterate through the returned Python list and print the field name, field type, and field
length of each field to the Interactive Window.
▪ To concatenate a number to a string, use the str function.
▪ Remember that each field returned from the List function is an object.
Run the script.
List the raster datasets with names that start with the letter "e" that are stored in the C:\
Student\PYTH\Database\Tahoe\Emer folder.
Iterate through the returned Python list and delete each raster.
(Hint: There is a geoprocessing tool in the Data Management toolbox that will delete
data.)
Open ArcCatalog to verify that the Emer folder does not contain raster datasets that begin
with the letter "e." (You may need to refresh the folder if you already had ArcCatalog
open.)
Lesson review
1. What do all List functions on the geoprocessor return?
______________________________________________________________________________
______________________________________________________________________________
2. To loop through a Python list that gets returned from a List function, which of the following
would you use?
a. A for loop.
b. A range loop.
c. A while loop.
______________________________________________________________________________
______________________________________________________________________________
______________________________________________________________________________
______________________________________________________________________________
______________________________________________________________________________
______________________________________________________________________________
______________________________________________________________________________
______________________________________________________________________________
______________________________________________________________________________
______________________________________________________________________________
______________________________________________________________________________
1. The ListFeatureClasses function returns a Python list. What data type is the returned
value? What do the values contain?
A String value is returned that contains the names of the feature classes.
2. The ListFields function returns a Python list that contains Field objects. What are some
of the field object properties that you can access?
Some field object properties include name, type, length, scale, aliasName, etc.
3. Referring to the code sample for the ListFields function, how do you iterate through the
Python list that the function returns?
1. List datasets.
import arcpy
arcpy.env.workspace = "C:\\Student\\PYTH\\Database\\World.gdb"
for ds in dsList:
print ds
import arcpy
arcpy.env.workspace = "C:/Student/PYTH/Database/SanDiego.gdb"
import arcpy
arcpy.env.workspace = "C:/Student/PYTH/Database/Tahoe/Emer"
Lesson review
2. To loop through a Python list that gets returned from a List function, which of the following
would you use?
a. A for loop.
Exercise solution
ListGDB.py
# Author: ESRI
# Date:
# Purpose: Lists all the geodatabases in a folder.
# Iterate through all the geodatabases and print the name of each
# geodatabase to the Interactive Window.
for gdb in gdbList:
print gdb
ListFields.py
# Author: ESRI
# Date:
# Purpose: Lists all the fields in a feature class.
DeleteRasters.py
# Author: ESRI
# Date:
# Purpose: Lists all the rasters that start with 'e'
# in the Tahoe\Emer folder.
# List all the rasters that start with 'e' in the current workspace
# rdList is a Python List returned from the ListRasters function.
rdList = arcpy.ListRasters("e*")
#Iterate through the list and call the Delete tool passing in
# the name of the raster to delete.
for ras in rdList:
arcpy.Delete_management(ras)
Introduction
A cursor is a data object that can be used to iterate over a set of rows in a table or feature class to
read field values, update field values or insert new rows. By using cursors, you can quickly
process subsets of data for mass updates of field values or generate reports on existing field
values. You can use a cursor to read a text file and create new rows in the table.
Learning objectives
6-1
Creating and updating data with Cursor objects
Cursor objects
There are many reasons to work with cursors. The most typical workflows that use cursors use
them to mass update field values (such as when a new field is added), to summarize and report
on field values, and to mass insert new rows into a table or feature class.
In this lesson, you will write Python scripts that use cursors to read values from fields and to
update a field value by concatenating the values from other fields. One of the first steps to
writing a script is to gain an understanding of the resources that the script needs to perform the
required tasks.
1. What is a cursor?
______________________________________________________________________________
______________________________________________________________________________
In the Help, expand Functions > Cursors and review the three cursor topics.
3. Which cursor function can be used to create a cursor object that retrieves rows?
______________________________________________________________________________
4. If your script places new values in fields for existing rows, which cursor function would you
use?
______________________________________________________________________________
Cursor functions
SearchCursor function
UpdateCursor function
# Iterate through the rows in the cursor and update the address
for row in cur:
row.Addr = "1900 ZOO PLACE"
cur.updateRow(row)
del cur, row
InsertCursor function
cur = arcpy.SearchCursor("MajorAttractions")
for row in cur:
fieldName = "TYPE"
# The next two lines are equivalent
value = row.getValue(fieldName)
value = row.TYPE
import arcpy
import arcpy
import arcpy
# Variable reference for the SQL where clause to pass to the cursor.
# When applied limits the records returned by the cursor
whereClause = "EMP > 500"
# Loop through the results and store them in the python dictionary
for place in src:
print place.getValue("name")
majorAttractionLookup[place.getValue("name")] = place.EMP
In this exercise, you will use the SearchCursor function to read field values from a feature class.
Then you will use the UpdateCursor function to place values in a field based on values from two
other fields.
In this exercise, you will:
▪ Access field values from a feature class
▪ Add and update a field
▪ Optionally, check for a field
1. What ArcPy List function can you use to determine the field names of a feature class or
table?
______________________________________________________________________________
2. When iterating through the Python List that this function returns, how can you determine
the name of each field?
______________________________________________________________________________
______________________________________________________________________________
______________________________________________________________________________
Use the AddField geoprocessing tool to add a Text field called Full_Address to the
C:\Student\PYTH\Database\Redlands.gdb\Hospitals feature class.
4. Which type of cursor will allow you to write new attribute values to existing rows in a
feature class?
______________________________________________________________________________
Populate your new field with values from the ARC_Street and CITY fields. Be sure to
include a comma and space when concatenating the field values.
Because cursors place locks on the dataset that is being updated, add code to the bottom of
your script to delete the cursor.
Open ArcCatalog and view the updated table for the Hospitals feature class.
The Full_Address field that you added to the Hospitals feature class contains the values from
both the ARC_Street and CITY fields, separated by a comma and a space.
Close ArcCatalog.
If you have time, complete the optional step; otherwise, close the UpdateField.py script.
5. Which Python built-in function will return the number of items in a Python list?
______________________________________________________________________________
Above the code that adds the new field, modify the script to do the following:
▪ Check if the Full_Address field exists.
▪ If the field does not exist, add it to the Hospitals feature class.
▪ If the field already exists, print a message to the Interactive Window.
Check for syntax errors and run the script.
You created the field in the previous step, so the Interactive Window prints your message which
indicates that the field already exists.
In your script, you used the hard-coded Hospitals value for the feature class and the
Full_Address value for the new field. When a hard-coded value is used many times throughout
a script, a best practice is to store that value in a variable.
Using variables in the place of hard-coded values can make your script easier to modify. If you
decide to reuse the script on a different feature class and/or field, only the variable values would
need to be changed.
Above the code that checks for the Full_Address field, store the following values in
variables, then use the variables throughout the script:
▪ Hospitals feature class
▪ Full_Address field
6. When the field name is stored in a variable, instead of using the row.fieldName property to
assign the field value to each row in the cursor, what method should you use?
______________________________________________________________________________
In your for loop, modify the code to use the appropriate method to assign the value to the
row.
Lesson review
1. Return the maximum and minimum values of LAND_VALUE from the Corvallis Parcel
feature class.
▪ Write a single line of code.
▪ Refer to the ArcGIS Help topic: SearchCursor.
______________________________________________________________________________
______________________________________________________________________________
______________________________________________________________________________
Best practices
When working with cursors:
▪ Use variables instead of hard-coded values where possible. This makes your code
reusable, more flexible, and easier to debug.
▪ When getting or updating field values for the Row object returned by the cursor, use the
methods, row.getValue() and row.setValue(). This allows for variable substitution of
the row field names.
▪ Use del cur and del row at the end of your script to remove any locks on the feature
class or table. All cursors place locks on the feature class or table, which will not be
removed until either the script closes or the del statement is used.
▪ Before you can use an update cursor or insert cursor on a feature class or table, the cursor
must obtain exclusive access to the data; therefore, the feature class or table cannot also
be open in ArcCatalog or ArcMap.
Cursor objects
1. What is a cursor?
A cursor is a data object that can be used to read and update attributes.
3. Which cursor function can be used to create a cursor object that retrieves rows?
4. If your script places new values in fields for existing rows, which cursor function would you
use?
The UpdateCursor function creates a cursor that can update field values or delete rows.
1. What ArcPy List function can you use to determine the field names of a feature class or
table?
arcpy.ListFields()
2. When iterating through the Python List that this function returns, how can you determine
the name of each field?
900 F ST
CHULA VISTA, CA 91910
4. Which type of cursor will allow you to write new attribute values to existing rows in a
feature class?
Update cursor. (A search cursor only allows you to read values and an insert cursor only
allows you to add new rows.)
5. Which Python built-in function will return the number of items in a Python list?
len
6. When the field name is stored in a variable, instead of using the row.fieldName property to
assign the field value to each row in the cursor, what method should you use?
row.setValue()
Lesson review
1. Return the maximum and minimum values of LAND_VALUE from the Corvallis Parcel
feature class.
▪ Write a single line of code.
▪ Refer to the ArcGIS Help topic: SearchCursor.
rows = arcpy.SearchCursor("C:/Student/Data/Corvallis.gdb/Parcel",
"", "", "", LAND_VALUE D")
Exercise solution
Attractions.py
# Author: ESRI
# Purpose: Prints the name, address, city, state and zip of each feature
# in the MajorAttractions feature class.
UpdateField.py
# Author: ESRI
# Purpose: Add a field to a feature class and update that
# field using the values from two other fields.
CheckAndUpdateField.py
# Author: ESRI
# Purpose: Add a field to a feature class only if it does NOT already exist
# and update that field using the values from two other fields.
import arcpy
# Set workspace.
arcpy.env.workspace = "C:\\Student\\PYTH\\Database\\Redlands.gdb"
Introduction
Up to this point, you have mostly been writing scripts that use hard-coded paths and variables
with hard-coded values. This can work fine for scripts that need to be run on the same set of
data from time to time, but what if you want to run the script multiple times and specify a
different set of input or output data? Or what if the data was to move to a different storage
location?
By adding arguments for the paths and variables to your scripts, you can make the script more
dynamic and better fit the scripts into your automation work flows. A script that has been made
dynamic can be added to ArcToolbox as a custom script tool. This process allows you to define
the arguments for the script, which are supplied by the script tool dialog box at run time.
Learning objectives
Key terms
7-1
Running your scripts in ArcToolbox
When scripts contain hardcoded values, such as feature class names or paths to data, the script
knows exactly where to go to access the data and work with the defined values. But what if you
want to run the script multiple times, specifying a different feature class or data location each
time? Or what if you want the end user to select the feature class before running the script?
You can make your input and output values in your script dynamic by adding arguments to the
script.
Note: You may notice that arguments are also referred to as parameters; both words are
used interchangeably.
There are two functions that you can use to create an argument in your script.
Assign one of the following functions to any variable or value in your script:
You can execute scripts that use these functions via the methods indicated below.
Note: The sys.argv[] function has a limit of 1024 characters. If you are using a
script tool that accepts MultiValue inputs, use the GetParameterAsText()
function instead.
▪ You do not need to import the sys module, which results in less overhead.
▪ Your script will be more readable if you use the SetParameterAsText function in
conjunction with the GetParameterAsText function.
(Both of these ArcPy functions start their parameter numbering at 0.)
1. When you run a script tool in ArcToolbox, what benefits does the tool dialog box provide?
______________________________________________________________________________
______________________________________________________________________________
2. When arguments are passed to a script that is run in PythonWin, how do you indicate the
separation of the arguments?
______________________________________________________________________________
To create a script tool, right-click the custom toolbox and choose Add > Script.
The Add Script wizard contains three panels.
General properties
Provide the script tool's name,
display label, description (for
the help text), and stylesheet
(the default stylesheets are
sufficient for most purposes).
Script location
Provide the file that will be
executed from the tool (i.e.,
Python script, AML, or EXE).
Parameter properties
Provide the parameters
that correspond to each
sys.argv[ ] or
GetParameterAsText()
argument in the script.
For more information about parameter properties, in the ArcGIS Desktop Help, navigate to:
▪ Professional Library >
▪ Geoprocessing >
▪ Creating tools >
▪ Creating script tools with Python scripts >
▪ Setting script tool parameters
ToolValidator
All script tools come with the ToolValidator class, which enables the validation of parameters.
This could include setting default values for parameters based on what you set for other
parameters or the license available, or enabling or disabling a parameter based on the tool dialog
inputs.
If the script tool is placed in a model, the ToolValidator can create the required schema for
describing the derived output of the tool to the model and give you the same capabilities of a
system tool in a model, such as providing a derived output from the tool.
The following table from the ArcGIS Desktop Help shows the ToolValidator methods found on
all script tools:
While you cannot edit the ToolValidator for a system script tool, you can edit the ToolValidator
class methods for any script tool located in a custom toolbox.
Code samples
For your reference and study, here is some sample code that shows the use of the
updateParameter method and the updateMessages method on the ToolValidator class, taken
from the Hot Spot tool and the ArcGIS Desktop Help.
if self.params[0].value:
if not self.params[6].altered:
extent = string.split(arcpy.Describe(self.params[0].value).extent, " ")
width = float(extent[2]) - float(extent[0])
height = float(extent[3]) - float(extent[1])
if width > height:
self.params[6].value = width / 100
else:
self.params[6].value = height / 100
return
def updateMessages(self):
return
Customize a message
def updateMessages(self):
self.params[6].clearMessage()
class ToolValidator:
def __init__(self):
import arcpy
self.params = arcpy.GetParameterInfo()
def initializeParameters(self):
return
def updateParameters(self):
# Provide default values for "file format type" and
# "feature type in file"
#
if not self.params[1].altered:
self.params[1].value = "OLD_FORMAT"
if not self.params[2].altered:
self.params[2].value = "POINT"
# Update the value list filter of the "feature type in file" parameter
# depending on the type of file (old vs. new format) input
#
if self.params[1].value == "OLD_FORMAT":
self.params[2].filter.list = ["POINT", "LINE", "POLYGON"]
elif self.params[1].value == "NEW_FORMAT":
self.params[2].filter.list = ["POINT", "LINE", "POLYGON",
"POINT_WITH_ANNO",
"LINE_WITH_ANNO",
"POLYGON_WITH_ANNO"]
return
def updateMessages(self):
return
In this exercise, you will make dynamic input and output arguments for variable values. You
will also learn how to run scripts with dynamic arguments from PythonWin, the Python
window in ArcMap, and in ArcToolbox.
In this exercise, you will:
▪ Run scripts using hard-coded and dynamic values
▪ Run a script from PythonWin
▪ Attach a script to a tool
▪ Run script tools from ArcToolbox and in the Python window
This script copies selected features from one feature class into a new feature class. The
MakeFeatureLayer tool makes a temporary layer that holds selected features from the C:\
Student\PYTH\Database\World\Country.shp. The CopyFeatures tool copies the selected
features into the new Country feature class.
Read through the script's comments. Make sure you understand the script before you
continue. If you are having difficulties, ask your instructor for help.
Notice that the following input and output values are hard-coded in this script—The user has no
input or output choices:
▪ inFC
▪ outFC
▪ expression
▪ fieldInfo
This script copied all the features from the ...\Database\World\Country.shp into the
...\Database\World.gdb\Country feature class. The script did the job that it was supposed to
do. However, this script has limited use because all the values are hard-coded. This script would
suit a wider audience if all input and output arguments were dynamic.
In the next step, you will make this script more flexible.
Minimize ArcCatalog.
inFC = arcpy.GetParameterAsText(0)
outFC = arcpy.GetParameterAsText(1)
expression = arcpy.GetParameterAsText(2)
fieldInfo = arcpy.GetParameterAsText(3)
You will copy all the features in the ...\Database\World\Cities.shp into a new feature class in
the ...\Database\World.gdb.
In the Run Script dialog box, for Arguments, type the following arguments on a single line,
separated by spaces:
C:\Student\PYTH\Database\World\Cities.shp
C:\Student\PYTH\Database\World.gdb\Cities
""
""
When the script has finished executing, verify that the C:\Student\PYTH\Database\
World.gdb\Cities feature class was created.
This script ran and performed the job that it was supposed to do. However, this time the script
accepted dynamic input from the user, making the script more flexible. In the remaining steps,
you will learn how to run a script with arguments from other environments, including
ArcToolbox and the Python window.
Before you add a script to ArcToolbox, you need to create a toolbox to store the script.
In the Custom Tools Properties dialog box, for Alias, type custom.
Click OK.
Next, you will attach the FC2FC.py script to a tool in the Custom Tools toolbox.
Right-click the Custom Tools toolbox and choose Add > Script.
The first panel of the Add Script wizard asks for the script tool's Name, Label, and Description.
The Name is used to execute the script tool from the Command Line window or from another
script. The Name cannot contain spaces. The Label is the display name for the script (i.e., how
it will appear in the ArcToolbox window). Labels may contain spaces.
Click Next.
Click Next.
Next, you will enter the four script arguments and their parameter properties.
Click Finish.
In the next step, you will run the script tool from ArcToolbox.
In ArcToolbox, double-click the Feature class to feature class script tool to open it.
The dialog box prompts you for the four arguments that you specified in the Add Script wizard.
Two arguments are optional: Expression and Field information.
In the Feature class to feature class dialog box, click Show Help.
The description that you wrote for the tool displays in the tool's help panel.
The Browse button is available because you assigned this argument the Feature Class data type.
The tool's dialog box is smart enough to supply a Browse button for feature classes, feature
datasets, workspaces, and so on.
In the Input feature class dialog box, browse to and add the C:\Student\PYTH\
Database\World\Country.shp.
Notice that the field names are added to the Field information list. This is because you set the
Obtained From parameter property to the Input feature class and also the Field information
parameters.
In the Query Builder dialog box, create the following SQL statement.
"CNTRY_NAME" = 'Mongolia'
Notice that all the field and attribute values are available in the Query Builder dialog box. This
is because you set the Obtained From parameter property between the Input feature class and
the Expression.
Click OK.
Verify that your Feature class to feature class dialog box matches the following graphic:
Click OK.
This tool will copy the Mongolia feature in the ...\Database\World\Country.shp to a new
feature class in the ...\Database\World.gdb\Mongolia feature dataset.
Your script tool is now part of the geoprocessing framework. At this point, you can run the tool
from the Python window, add the tool to a model, run the script from another script, or assign
help documentation to the tool.
Open the Python window (Geoprocessing > Python). Move the Python window to a
location where you can see the entire window.
By default, the Python window imports the ArcPy site package, so you are ready to issue
Python commands, statements, and ArcPy commands.
In the Python window, at the >>> prompt, type the following code:
arcpy.ImportToolbox(r"C:\Student\PYTH\Exercise07\Custom Tools.tbx")
arcpy.FeaturesToFeatures_custom("C:\Student\PYTH\Database\World\Lakes.shp",
"C:\Student\PYTH\Database\World.gdb\Lakes")
Verify that the Lakes feature class has been created in the World.gdb file geodatabase.
In the previous exercise, you learned how to attach a script to a script tool. In this exercise, you
will attach another script to a script tool, and you will use the arcpy.GetParameterAsText()
function. You will also learn how to set the Filter, MultiValue, and Default properties for an
argument in a script tool.
In this exercise, you will:
▪ Replace hard-coded values with dynamic values in a script
▪ Attach a script to a tool in ArcToolbox
▪ Run a script tool
This script buffers multiple feature classes at a specified distance. All the values are currently
hard-coded. You will make these values dynamic using the arcpy.GetParameterAsText()
function.
Return to ArcCatalog.
In ArcToolbox, right-click the Custom Tools toolbox and choose Add > Script.
Click Next.
Running the script tool in process will ensure that the Python script does not start a separate
process to run. This can enhance the performance of your script tools when run in ArcGIS
Desktop.
Click Next.
Now you will specify the script arguments and their properties. Three variables need to be set as
arguments: inFCs, outWS, and dist.
By setting a range filter, you are restricting the user to entering a buffer distance between 500
and 1500 feet.
In the Buffer multiple feature classes dialog box, for Feature classes to buffer, browse to
the C:\Student\PYTH\Database\SanDiego.gdb and add the Railroads and Freeways
feature classes.
Notice that you can add multiple feature classes to the list. This is because you set the
MultiValue property to Yes for the Feature classes to buffer. Also notice that the Output
location displays a default value. This is another property that you set when you created the
script tool.
Click OK.
______________________________________________________________________________
If necessary, close the progress window when the tool has finished executing.
Verify that the two new feature classes were created in the C:\Student\PYTH folder.
Close ArcCatalog.
Lesson review
1. How do you make a Python script dynamic?
______________________________________________________________________________
______________________________________________________________________________
______________________________________________________________________________
1. When you run a script tool in ArcToolbox, what benefits does the tool dialog box provide?
The tool dialog box validates all inputs, checks to make sure the output data does not
exist, offers default values, and has a much shorter startup time.
2. When arguments are passed to a script that is run in PythonWin, how do you indicate the
separation of the arguments?
Lesson review
Exercise solution: 7A
FC2FC.py
# Author: ESRI
# Date:
# Purpose: Copy selected features from one feature class into
# a brand new feature class.
# Make a temporary layer to hold the selected features and altered fields.
# The selected features are determined by the expression variable.
# The altered fields are determined by the fieldInfo variable.
arcpy.MakeFeatureLayer_management(inFC, os.path.basename(outFC), expression,
os.path.dirname(outFC), fieldInfo)
# Copy selected features and altered fields to the output feature class.
arcpy.CopyFeatures_management(os.path.basename(outFC), outFC)
Exercise solution: 7B
Buffer.py
# Author: ESRI
# Date:
# Purpose: Creates buffers around specified feature classes.
# Buffer distance is restricted to 500 - 1500 feet.
# Output workspace.
outWS = arcpy.GetParameterAsText(1)
# Buffer distance.
dist = arcpy.GetParameterAsText(2)
Introduction
In Lesson 3, you worked with several different script debugging techniques. The techniques
focused on Python syntax and logic errors, but did not explore errors or exceptions that could be
generated by Python or by running the script in the geoprocessing framework.
In this lesson, you will examine how to handle an exception raised by Python, handle an arcpy
ExecuteError exception, and work with the Python traceback module to obtain detailed
information about the exception. Gracefully trapping for errors when the code executes makes
your script look more professional and efficient and can reduce user frustration.
Learning objectives
Key terms
▪ Errors:There are two types, syntax errors and exceptions. Syntax errors can be detected
and corrected before the script is executed.
▪ Exception:: An error that is detected during execution of the script.
8-1
Handling Python and ArcPy exceptions
Note: To learn more about error handling in scripts, refer to the ArcGIS Desktop Help:
▪ Professional Library >
▪ Geoprocessing >
▪ Geoprocessing with Python >
▪ Accessing tools >
▪ Error handling with Python
Using try..except
One of the simplest and possibly the easiest ways to catch exceptions in your scripts is to use the
try..except block. The code that you want to run in your script is placed inside the try block,
and code to handle the exception is placed in the except bock. When you execute (run) your
script, if any exception is detected in your code within the try block, Python jumps down to the
except block and executes that code.
The major advantage to using the try..except block is that your code will not fail with a
traceback message if an exception is detected while executing the code. The except block
handles the exception by running the code you have there.
Code that you place in the except block could include print statements for detailing the
exception and, if the script is using the ArcPy site package, for printing geoprocessing messages.
Using Exception as e
Using the Python Exception as e statement can be useful when you need some details on the
exception that occurred.
If the exception was generated by a Python error, you can print details of the exception by using
print e in the exception block.
try:
#
# Your code goes here
except Exception as e:
print "Error occurred"
print e
Using arcpy.ExecuteError
There may be times when you would like to handle an exception generated from the
geoprocessor separately from any Python errors. The arcpy.ExecuteError and
arcpy.ExecuteWarning exception classes can be raised when a geoprocessing tool encounters
an error or warning.
When the execution of a geoprocessing tool encounters an error, the arcpy.ExecuteError
exception class is raised. You can use the exception class in your script along with a print
statement to display the error.
Here's an example of a simple arcpy.ExecuteError exception handler in a script:
try:
#
# Your code goes here
except arcpy.ExecuteError:
print "Geoprocessing tool error occurred"
print arcpy.GetMessages(2)
arcpy.GetMessages()
Here's an example of using the traceback module with the sys module:
try:
# Your code goes here
except:
# Get the traceback object
tb = sys.exc_info()[2]
tbinfo = traceback.format_tb(tb)[0]
In the code sample, when an exception occurs, the except block will get the traceback object
and print out the traceback information, and then print any ArcPy error messages that had
occurred. For compatability with scripts run in ArcGIS Desktop or as a server task, the
arcpy.AddError function is used to pass the traceback and geoprocessing messages to the
dialog box and results window.
Implementing error handling in your scripts is always a good idea. If your script encounters an
exception, you can gracefully handle the error and not have the script crash on the end-user side.
Adding code to your script to handle any runtime error is a good programming practice.
In this exercise, you will:
▪ Incorporate a try..except block into an existing script
▪ Use the Exception as e handler
▪ Use the arcpy.ExecuteError exception class
▪ Use the traceback and sys modules
Click the Check button to check the syntax, then run the script—it will fail with a
traceback exception.
The script failed with an exception and printed a lot of error messages. A good script always has
code to handle exceptions and print more meaningful messages, which provide a more positive
experience to the end user.
To print more meaningful messages and to prevent the script from crashing, you will add error
handling code to the script.
Using your knowledge and skills, incorporate a try..except block into the script.
Within the except block, write code to add two print statements:
Check your script syntax and fix any errors that are detected.
______________________________________________________________________________
______________________________________________________________________________
3. Based on the error messages, how might you fix the problem?
______________________________________________________________________________
______________________________________________________________________________
______________________________________________________________________________
In the next step, you will work with the Exception as e handler.
Check your script syntax and fix any errors that occur.
In the Interactive Window, scroll down below any text and press the Enter key to display
the Python prompt.
4. Are the messages similar to the error messages in the previous step?
______________________________________________________________________________
Within the arcpy.ExecuteError handler, write code to print the following to the
Interactive Window:
▪ A message to indicate that a geoprocessing error occurred
▪ The geoprocessing error messages
Check your script syntax and fix any errors.
5. Do the geoprocessing messages in the Interactive Window look any different than they did
in the previous step?
______________________________________________________________________________
6. If a Python exception had occurred, would the arcpy.ExecuteError handler code display
any Python exceptions?
______________________________________________________________________________
In the final step, you will work with the the traceback module.
except:
# Get the traceback object
#
tb = sys.exc_info()[2]
tbinfo = traceback.format_tb(tb)[0]
# Return python error messages for use in script tool or Python window
#
arcpy.AddError(pymsg)
arcpy.AddError(msgs)
Clear the Interactive Window. (Right-click within it, choose Select All, then right-click
again and choose Cut).
Several error messages print to the Interactive Window. You may need to scroll up to see all of
them.
7. What are the two types of Python error messages that displayed?
______________________________________________________________________________
8. Is the Error Info message content sufficient for you to possibly fix the problem?
______________________________________________________________________________
9. Is the error message any different than the Error Info message?
______________________________________________________________________________
10. When using the traceback module, do you need to add code to handle ArcPy messages?
______________________________________________________________________________
In this exercise, you learned several techniques for handling both Python and ArcPy exceptions.
The technique you use in your scripts will depend on how you want to handle the exceptions
that may occur.
Lesson review
1. Which exception handling technique (covered in this lesson) provides the most error detail?
______________________________________________________________________________
______________________________________________________________________________
2. Which exception handlers will handle only geoprocessing tool errors and warnings?
______________________________________________________________________________
______________________________________________________________________________
______________________________________________________________________________
3. Write an except block that prints the error severity level geoprocessing messages to the
Interactive Window.
______________________________________________________________________________
______________________________________________________________________________
______________________________________________________________________________
Error 000732: Clip Features: Dataset ClipBoundary does not exist or is not supported.
3. Based on the error messages, how might you fix the problem?
Verify that the clipping feature does not exist. If it doesn't exist, create the feature class.
Check the shapetype of the feature class to verify that the featue class stores polygon
shapes.
Open the feature class in ArcMap and visually check the features.
4. Are the messages similar to the error messages in the previous step?
Yes, but there are fewer messages. Only the print and exception messages display.
5. Do the geoprocessing messages in the Interactive Window look any different than they did
in the previous step?
6. If a Python exception had occurred, would the arcpy.ExecuteError handler code display
any Python exceptions?
No, the arcpy.ExecuteError handler code only displays ArcPy Error exceptions.
7. What are the two types of Python error messages that displayed?
8. Is the Error Info message content sufficient for you to possibly fix the problem?
9. Is the error message any different than the Error Info message?
10. When using the traceback module, do you need to add code to handle ArcPy messages?
No. (Python exception messages and geoprocessing messages will both display).
Lesson review
1. Which exception handling technique (covered in this lesson) provides the most error detail?
The traceback module used in conjunction with the sys module can provide the most
detail.
2. Which exception handlers will handle only geoprocessing tool errors and warnings?
3. Write an except block that prints the error severity level geoprocessing messages to the
Interactive Window.
except:
print arcpy.GetMessages(2)
Introduction
In many geoprocessing workflows, you will run tools that use coordinate and geometry
information. There may be times when you do not necessarily want to go through the process of
creating a temporary feature class to store features such as a clipping rectangle for the Clip tool.
This would necessitate populating the feature class with a cursor, using the feature class in the
geoprocessing task, and then deleting the feature class. Geometry objects can be used instead for
the Clip tool's clipping layer input parameter to make the workflow simpler.
Geometry objects that can be created from scratch include Geometry, MultiPoint, Point,
Polyline, and Polygon. These can be empty geometry objects with no coordinate values, or can
be populated with coordinate pairs.
MultiPoint, Polyline and Polygon geometry objects use an array of coordinate pairs to construct
the geometry object shape.
Learning objectives
9-1
Creating and updating geometry objects
Key terms
Geometry object : Used to define a spatial location and associated geometric shape.
Geometry list: When the output parameter of a geoprocessing tool is set to an empty Geometry
object, the tool returns a list of Geometry objects.
g = arcpy.Geometry()
geomList = arcpy.Buffer("Freeways ", g, "10000 meters ")
area = 0
for geom in geomList:
area += geom.area
pnt= arcpy.Point()
featureList = []
coordList = [[1277000.0, 344000.0], [1283000.0, 344000.0],
[1283000.0, 336000.0], [1277000.0, 336000.0]]
Code samples
Point object
import arcpy
Polyline object
import arcpy
Polygon object
import arcpy
Extent object
import arcpy
# Syntax:
# Extent ({XMin}, {YMin}, {XMax}, {YMax}, {ZMin}, {ZMax}, {MMin}, {MMax})
import arcpy
Creation of geometry objects is quite easy. To create a new Point geometry, all you need is its
x,y coordinates. For Polyline geometry, you construct the vertices of the geometry using Point
objects that contain x,y coordinates, store the Point objects in an Array object, then pass the
Array object to the Polyline class constructor. The same methodology applies to creating new
Polygons, with the one additional step of adding the first point to the Array again at the end to
close the polygon ring, then pass the Array to the Polygon class constructor.
Once the geometry object has been created, it can be used to create new features or modify
existing features in feature classes. It can also be passed to a geoprocessing tool for both input or
output parameters. In this exercise, you will create a Polygon geometry object and pass it to the
Clip tool as the clipping layer. You will also create new geometry objects, populate them with
coordinate pairs, and store them as new features in a feature class.
In this exercise, you will:
▪ Create Point, Polyline, and Polygon geometry objects
▪ Insert new features into a feature class using an InsertCursor and geometry objects
▪ Create a Polygon geometry object and pass it to the Clip tool as the clipping layer
______________________________________________________________________________
2. What code syntax would you write to create a new Point geometry object, where X is 2000
and Y is 1000?
______________________________________________________________________________
Using your answer to the previous question, create a new Point geometry object that
reports its x,y coordinates to the Python Interactive Window.
Check the code syntax, run the script, and verify that the coordinates print to the
Interactive Window.
Return to the ArcGIS Help and review the topics for the Polyline and Polygon classes.
Notice that you will need both Point and Array objects to create and populate Polyline and
Polygon geometry objects.
Return to PythonWin.
Create a new Polyline geometry object based on the x,y coordinates provided below:
Note: For guidance, you may want to refer to the Polyline object code sample that
is provided on a preceding page in your workbook.
x-coordinate y-coordinate
100 200
200 400
300 700
600 800
500 700
In the Interactive Window, write the following line of code to verify that the polyline was
created successfully:
print polyline.pointCount
______________________________________________________________________________
Create a Polygon geometry object from the same list of coordinate pairs.
Note: You do not need to add the first point again to close the polygon. When you pass
the point array into arcpy.Polygon() it will automatically "rubber band" to
the first point. However, it is good practice to add the first point to the end of the
array. If you choose to add the first point to the end of the array, use this syntax:
point.X = coordList[0][0]
point.Y = coordList[0][1]
______________________________________________________________________________
Use these steps as a guide to write a script that inserts a new feature into a feature class:
▪ Create an Insert Cursor on the MajorAttractions feature class.
(Hint: Set the workspace before creating the cursor.)
▪ Create an empty Point object and populate it with the following values:
▪ X = 6284067.077
▪ Y = 1840118.986
▪ Create a new row on the cursor and populate the row with these values:
▪ Name = "Marthas Place"
▪ CityNM = "San Diego"
▪ Zip = 92109
▪ Populate the shape field with your Point object and insert the row into the cursor.
▪ Remember to delete the cursor to remove any locks on the feature class.
Start ArcMap.
Browse to the Exercise09 folder, select the CreateFeatures.py, and click Open.
It is good practice to refresh the view after the feature has been added.
To verify that your script successfully added the new feature, use the Find tool to locate
and zoom to Marthas Place.
Your next task is to update the location of Balboa Park to the new entrance that was opened last
week.
5. What are the coordinates for the Balboa Park point feature?
(Hint: Use the Identify tool.)
______________________________________________________________________________
In the script, modify the values of the Point's X and Y properties to the following:
▪ X = 6285430.0
▪ Y = 1844965.66
Verify that the Balboa Park point feature location has been updated. (Use the Identify
tool.)
Return to PythonWin.
Create a new Python script named ClipGeom.py and save it to your Exercise09 folder.
Create a new empty Point object and a new empty Array object.
x-coordinate y-coordinate
1277000.0 344000.0
1283000.0 344000.0
1283000.0 336000.0
1277000.0 336000.0
Clip the StPaved feature class against the Polygon geometry object to create the
DowntownStreets feature class.
Choose the correct Clip geoprocessing tool. (One of the Clip tools only works
with rasters.)
Confirm that the check box is enabled to Overwrite the outputs of geoprocessing
operations.
Add the DowntownStreets feature class to the map and verify that the Clip tool worked
correctly.
In the Table of Contents, right-click the DowntownStreets layer and choose Remove.
Load the ClipGeom.py script into the Python window and press Enter to run the script.
Lesson review
1.
In order to create a Polygon geometry object, you must first create a ______ geometry object
2. List some ways you might use geometry objects in your geoprocessing workflows.
______________________________________________________________________________
______________________________________________________________________________
______________________________________________________________________________
# Add the server toolbox through the url to the server toolbox.
# This sample will use the population summary geoprocessing
# service available on sample server
try:
arcpy.ImportToolbox("http://sampleserver1.arcgisonline.com/ArcGIS/services;
Demographics/ESRI_Population_World")
arcpy.ImportToolbox("http://sampleserver1.arcgisonline.com/ArcGIS/services;
Network/ESRI_DriveTime_US")
except:
print "Toolbox not found or internet connection not there"
print "Check the internet settings to the Sample server"
sys.exit[1]
# Create a spatialReference
sf = arcpy.SpatialReference()
sf.factoryCode = 4326
# Load the featureclass into the featureset as input to the server tool
networkFS.load(tempFC.getOutput(0))
# Get output from Drive time analysis tool available on sample server
networkOutput = netRes.getOutput(0)
# Use the get count tool to determine if there are features in the result
netResNum = arcpy.GetCount_management(networkOutput)
if populationResultNum == 0:
print "Problem encountered with the population summary"
sys.exit[1]
else:
src = arcpy.SearchCursor(popsummaryResult.getOutput(0))
row = src.next()
totalPop = row.SUM
print totalPop
x,y coordinates
2. What code syntax would you write to create a new Point geometry object, where X is 2000
and Y is 1000?
5. What are the coordinates for the Balboa Park point feature?
(Hint: Use the Identify tool.)
Lesson review
1. In order to create a Polygon geometry object, you must first create a Point geometry object
and an Array object.
2. List some ways you might use geometry objects in your geoprocessing workflows.
Exercise solution
CreateGeomObjects.py
import arcpy
pnt = arcpy.Point()
array = arcpy.Array()
coordList = [[100,200], [200,400], [300,700], [600,800], [500,700]]
polyline = arcpy.Polyline(array)
pnt = arcpy.Point()
array = arcpy.Array()
coordList = [[100,200], [200,400], [300,700], [600,800], [500,700]]
pnt.X = coordList[0][0]
pnt.Y = coordList[0][1]
polygon = arcpy.Polygon(array)
CreateFeatures.py
import arcpy
cur = arcpy.InsertCursor("MajorAttractions")
pnt = arcpy.Point()
pnt.X = 6284067.077
pnt.Y = 1840118.986
row = cur.newRow()
row.Name = "Marthas Place"
row.CityNM = "San Diego"
row.Zip = 92109
row.Shape = pnt
cur.insertRow(row)
del cur
UpdateFeatures.py
import arcpy
arcpy.env.workspace = "C:/Student/PYTH/Database/SanDiego.gdb"
cur = arcpy.UpdateCursor("MajorAttractions", "NAME = 'BALBOA PARK'")
pnt = arcpy.Point()
pnt.X = 6285430.0
pnt.Y = 1844965.66
del cur
arcpy.RefreshActiveView()
ClipGeom.py
import arcpy
arcpy.env.workspace = "C:/Student/PYTH/Exercise09/Corvallis.gdb"
pnt = arcpy.Point()
ary = arcpy.Array()
pnt.X = coordList[0][0]
pnt.Y = coordList[0][1]
ary.add(pnt)
clipPoly = arcpy.Polygon(ary)
Introduction
Automating the process of creating new geodatabases, feature classes, and tables can be
advantageous when designing, testing, and implementing a new GIS system. You can easily
make changes to schema, field names, and other components as needed.
What if you need to create a new feature class as a subset of a larger feature class? How about if
field names need to change to fit a new requirement? What are your options in this regard? You
have a couple of different paths you can choose to make the changes:
▪ Use ArcCatalog and make the changes by hand.
▪ Create a model or script and automate the process.
▪ Create subsets of data by making a feature layer or table view, then copy the features/
rows to a new feature class or table.
The Geoprocessing tools MakeFeatureLayer and MakeTableView both accept a SQL
expression and a FieldInfo object as their parameters. Once the FeatureLayer or TableView
object is created in memory, the CopyFeatures tool can be used to write the FeatureLayer
features to a feature class and/or the CopyRows tool can write the TableView rows to a new
table.
In the case of just changing a field, you can create a FieldInfo object detailing the change, create
a FeatureLayer or TableView object using the FieldInfo object, then copy the features/rows to a
new feature class/table.
10-1
Manipulating data schema and working with subsets of data
Learning objectives
Key terms
1.
Which tools create or manage feature layers and table views?
___________________
_________________
________________
____________________
___________________
__________________________
_________________________
______________________________________________________________________________
______________________________________________________________________________
3. What is the main benefit of using a feature layer as input to a geoprocessing tool?
______________________________________________________________________________
4. What geoprocessing tool can you use to make a feature layer permanent?
______________________________________________________________________________
Workflow problem
Report on road mileage in commissioner district
Syntax
arcpy.AddFieldDelimiters(datasource, field)
Code sample
#~~~~~~~~~~~~~~~~~~~~~~~~~~
# Construct a properly delimited
# SQL expression based on the workspace
#
#~~~~~~~~~~~~~~~~~~~~~~~~~~
There are times when you may need to create a subset of features from a feature class or layer in
your map, make some changes to the fields in the subset, and copy them to a new feature class
for more processing. This exercise will cover a sample workflow to accomplish this task.
In this exercise, you will write a Python script that will:
▪ Construct a SQL expression with proper field delimiters
▪ Create a FeatureLayer that uses the SQL expression to create a subset of features
▪ Create a second FeatureLayer for a spatial selection
▪ Perform a spatial selection using a specified distance
▪ Apply a FieldInfo object on the result of the spatial selection to hide fields
▪ Use the CopyFeatures geoprocessing tool to create a new FeatureClass from the subset
The City of Corvallis will be holding a special fundraiser at Central Park. Your task is to identify
the parking meters that are within a 500-foot distance of Central Park. The meters will be
programmed to charge a special reduced rate for the event.
Save the script to your Exercise10 folder with the name CreateCentralParkMeters.py.
Import the ArcPy site package and set the workspace environment setting to
"C:/Student/PYTH/Database/Corvallis.gdb"
In order to create a FeatureLayer that will contain only the Central Park feature, you will need
to construct a SQL expression with the correct delimiters around the field name.
Write code to create a FeatureLayer that will contain the Central Park feature.
▪ in_features: "Parks"
▪ out_layer: "Central Park"
▪ where_clause: sqlExp
Check the syntax of your script. Do not run the script yet.
Using the addField method on fldInfo, write code to make these schema changes:
▪ "RECCFLAG", "", "HIDDEN", ""
▪ "RECAFLAG", "", "HIDDEN", ""
▪ "METER_NUM", "METERNUM", "VISIBLE, ""
Create a new FeatureLayer for the Parking Meters. You can use a pair of double-quotes to
skip a parameter.
▪ in_features = "ParkingMeters"
▪ out_layer = "METERS"
▪ where_clause = ""
▪ workspace = ""
▪ field_info = fldInfo
Now that you have a FeatureLayer containing parking meters with the desired schema changes,
you are ready to select all the parking meters that are within 500 feet of the Central Park feature.
In the ArcGIS Desktop Help, review the parameters for the SelectLayerByLocation tool.
______________________________________________________________________________
______________________________________________________________________________
Using the SelectLayerByLocation tool, write code to select parking meters that are
within 500 feet of Central Park.
▪ in_layer = "METERS"
▪ overlap_type = use your answer to the previous question
▪ select_features = "Central Park"
▪ search_distance = "500 feet"
▪ selection_type = use your answer to the previous question
Your final step is to create a new feature class from the selected meters.
To check the results of your script, use the GetCount_management tool. You can also open
ArcMap, add the feature class, and open the attribute table.
______________________________________________________________________________
Lesson review
1. What are two geoprocessing tools that must use a feature layer to make selections?
______________________________________________________________________________
______________________________________________________________________________
2. Using a FieldInfo object, what kinds of schema changes can you make on a field?
______________________________________________________________________________
______________________________________________________________________________
______________________________________________________________________________
3. If you set a field as hidden in a FieldInfo object, the field will still be available in the Feature
Layer.
a. True
b. False
Tools that create and manage feature layers and table views
1.
Which tools create or manage feature layers and table views?
Make Feature Layer
Make Query Table
Make Table View
Make XY Event Layer
Save To Layer File
Select Layer By Attribute
Select Layer By Location
3. What is the main benefit of using a feature layer as input to a geoprocessing tool?
4. What geoprocessing tool can you use to make a feature layer permanent?
176
Lesson review
1. What are two geoprocessing tools that must use a feature layer to make selections?
SelectLayerByAttribute, SelectLayerByLocation
2. Using a FieldInfo object, what kinds of schema changes can you make on a field?
▪ Rename a field
▪ Make the field hidden or visible
▪ Set a split rule
3. If you set a field as hidden in a FieldInfo object, the field will still be available in the Feature
Layer.
b. False
Exercise solution
CreateCentralParkMeters.py
# Import arcPy site package and set the workspace environment setting
import arcpy
arcpy.env.workspace = "C:/Student/PYTH/Database/Corvallis.gdb"
Introduction
Making maps of your data is a key function of ArcGIS. The map may illustrate the results of
performing analysis, show certain patterns or relationships in your data, or simply convey
information about your data in an organized way.
This lesson will focus on automating the process of creating map books in ArcGIS. There are
two different ways to organize the layout of the map books. You can place a grid of polygons
over the extent of the features, which is called a grid index series, or the polygons can follow a
single or group of linear features, which is called a strip map index series.
There are many different types of map books that you can create in ArcGIS.
▪ Simple reference series map book: A set of map pages that use a single layout for a set of map
extents
▪ Reference series map book: Contains a set of map pages, including a title page, overview/
locator map, ancillary information, and contact information
▪ Thematic map book: Each map in the map series shows unique thematic maps of a single
location
▪ Reference map book with insets: A map series with inset maps for more detail, such as for a
densely populated area
11-1
Automating map production with ArcPy mapping module
Learning objectives
Key terms
A grid or fishnet of
polygons is placed
over the extent of
the features and
used to generate
the map pages.
import arcpy
from arcpy import env
env.workspace = "C:/Student/PYTH/Database/Corvallis.gdb"
A series of rectangular
polygons is placed over a
group of linear features and
used to generate the map
pages.
# Execute StripMapIndexFeatures
arcpy.StripMapIndexFeatures_cartography(inFeatures, outFeatureClass,
usePageUnit, scale, lenA, lenP)
In this exercise, you will write a script that creates a reference series map book.
Your script will:
▪ Create the map book PDF
▪ Append the title page to the map book PDF
▪ Export and append the grid index map series to the map book PDF
▪ Append the Contacts Info page to the map book PDF
▪ Save the map book PDF and view it
From your ..\PYTH\Exercise11 folder, open the script PublishMapBook.py and save it as
MyPublishMapBook.py.
Review the comments in the script to grasp a basic understanding of the processing
sequence.
In the script, you will write code below the relevant comments.
if os.path.exists(outDir + r"\MapPages.pdf"):
os.remove(outDir + r"\MapPages.pdf")
Check whether the map book PDF already exists, and if it does, remove it:
if os.path.exists(finalpdf_filename):
os.remove(finalpdf_filename)
1. Which variable can you use whenever you write code that includes the path to your
Exercise11 folder?
______________________________________________________________________________
Best practice:
▪ Save your work often.
▪ Click Check to run the Tab Nanny.
▪ Resolve any syntax errors.
Note: To learn more about exporting data driven pages, go to the ArcGIS Desktop Help
and navigate to:
▪ Professional Library >
▪ Mapping and Visualization >
▪ Automating map workflows >
▪ Data driven pages >
▪ Exporting Data Driven Pages
Create a MapDocument object (Hint: Use the variable that includes the path to your
Exercise11 folder):
▪ Call the arcpy.mapping.MapDocument() function.
▪ For the argument, pass in the path to PlainsView.mxd.
▪ Store the result in a variable named mxd.
Next, you will export the map document that contains the data driven pages to a multi-page
PDF.
Update the properties for viewing in Adobe Reader and save the PDF:
▪ Call the updateDocProperties() function on finalPDF.
▪ Pass in the following arguments:
▪ pdf_open_view = "USE_THUMBS"
▪ pdf_layout = "SINGLE_PAGE"
▪ Call the saveAndClose() function on finalPDF (with no arguments).
Delete the references to mxd and finalPDF.
Print a message to tell the user that the creation of the map book is complete.
2. Are the pages printed from Data View or Layout View? How can you tell?
______________________________________________________________________________
Lesson review
1. Can you enable Data Driven Pages from a script?
______________________________________________________________________________
______________________________________________________________________________
______________________________________________________________________________
______________________________________________________________________________
1. Which variable can you use whenever you write code that includes the path to your
Exercise11 folder?
outDir
2. Are the pages printed from Data View or Layout View? How can you tell?
Layout View. The map elements such as scale bar and north arrow display
Lesson review
Exercise solution
MyPublishMapBook.py
# PublishMapBook.py
# Author: <Your Name>
# Date: <Today>
# Purpose: Create map book pdf, output Data Driven Pages series from
# mxd, assemble map book and save.
# Check whether the final map book PDF exists. If it does, delete it.
if os.path.exists(finalpdf_filename):
os.remove(finalpdf_filename)
# Done. Clean up and let user know the process has finished.
del mxd, finalPDF
print "Creation of map book complete"
Permitted Uses:
▪ Licensee may run the setup and install one (1) copy of the Training Course onto a
permanent electronic storage device and reproduce one (1) copy of the Training Course
and/or any online documentation in hard-copy format for Licensee's own personal use
only.
▪ Licensee may use one (1) copy of the Training Course on a single processing unit.
▪ Licensee may make only one (1) copy of the original Training Course for archival
purposes during the term of this Agreement, unless the right to make additional copies is
granted to Licensee in writing by Esri.
▪ Licensee may use the Training Course provided by Esri for the stated purpose of
Licensee's own personal GIS training and education.
Uses Not Permitted:
▪ Licensee shall not sell, rent, lease, sublicense, lend, assign, time-share, or transfer, in
whole or in part, or provide unlicensed third parties access to the Training Course, any
updates, or Licensee's rights under this Agreement.
▪ Licensee shall not separate the component parts of the Training Course for use on more
than one (1) computer, used in conjunction with any other software package, and/or
merged and compiled into a separate database(s) for other analytical uses.
▪ Licensee shall not reverse engineer, decompile, or disassemble the Training Course,
except and only to the extent that such activity is expressly permitted by applicable law
notwithstanding this restriction.
▪ Licensee shall not make any attempt to circumvent the technological measure(s) (e.g.,
software or hardware key) that effectively controls access to the Training Course, except
and only to the extent that such activity is expressly permitted by applicable law
notwithstanding this restriction.
▪ Licensee shall not remove or obscure any copyright, trademark, and/or proprietary
rights notices of Esri or its licensor(s).
Term: The license granted by this Agreement shall commence upon Licensee's receipt of the
Training Course and shall continue until such time that (1) Licensee elects to discontinue use of
the Training Course and terminates this Agreement or (2) Esri terminates for Licensee's material
breach of this Agreement. The Agreement shall automatically terminate without notice if
Licensee fails to comply with any provision of this Agreement. Upon termination of this
Agreement in either instance, Licensee shall return to Esri or destroy all copies of the Training
Course, and any whole or partial copies, in any form and deliver evidence of such destruction to
Esri, which evidence shall be in a form acceptable to Esri in its sole discretion. The parties
hereby agree that all provisions that operate to protect the rights of Esri and its licensor(s) shall
remain in force should breach occur.
Limited Warranty and Disclaimer: Esri warrants that the media upon which the Training
Course is provided will be free from defects in materials and workmanship under normal use
and service for a period of ninety (90) days from the date of receipt.
EXCEPT FOR THE LIMITED WARRANTY SET FORTH ABOVE, THE TRAINING
COURSE CONTAINED THEREIN IS PROVIDED "AS-IS," WITHOUT WARRANTY OF
ANY KIND, EITHER EXPRESS OR IMPLIED, INCLUDING, BUT NOT LIMITED TO,
THE IMPLIED WARRANTIES OF MERCHANTABILITY, FITNESS FOR A
PARTICULAR PURPOSE, AND NONINFRINGEMENT. ESRI DOES NOT WARRANT
THAT THE TRAINING COURSE WILL MEET LICENSEE'S NEEDS OR
EXPECTATIONS; THAT THE USE OF THE TRAINING COURSE WILL BE
UNINTERRUPTED; OR THAT ALL NONCONFORMITIES, DEFECTS, OR ERRORS
CAN OR WILL BE CORRECTED. THE TRAINING DATABASE HAS BEEN OBTAINED
FROM SOURCES BELIEVED TO BE RELIABLE, BUT ITS ACCURACY AND
COMPLETENESS, AND THE OPINIONS BASED THEREON, ARE NOT
GUARANTEED. THE TRAINING DATABASE MAY CONTAIN SOME
NONCONFORMITIES, DEFECTS, ERRORS, AND/OR OMISSIONS. ESRI AND ITS
LICENSOR(S) DO NOT WARRANT THAT THE TRAINING DATABASE WILL MEET
LICENSEE'S NEEDS OR EXPECTATIONS, THAT THE USE OF THE TRAINING
DATABASE WILL BE UNINTERRUPTED, OR THAT ALL NONCONFORMITIES CAN
OR WILL BE CORRECTED. ESRI AND ITS LICENSOR(S) ARE NOT INVITING
RELIANCE ON THIS TRAINING DATABASE, AND LICENSEE SHOULD ALWAYS
VERIFY ACTUAL DATA, WHETHER MAP, SPATIAL, RASTER, TABULAR
INFORMATION, AND SO FORTH. THE DATA CONTAINED IN THIS PACKAGE IS
SUBJECT TO CHANGE WITHOUT NOTICE.
Exclusive Remedy and Limitation of Liability: During the warranty period, Licensee's exclusive
remedy and Esri's entire liability shall be the return of the license fee paid for the Training
Course upon the Licensee's deinstallation of all copies of the Training Course and providing a
Certification of Destruction in a form acceptable to Esri.
IN NO EVENT SHALL ESRI OR ITS LICENSOR(S) BE LIABLE TO LICENSEE FOR
COSTS OF PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES, LOST PROFITS,
LOST SALES OR BUSINESS EXPENDITURES, INVESTMENTS, OR COMMITMENTS
IN CONNECTION WITH ANY BUSINESS, LOSS OF ANY GOODWILL, OR FOR ANY
INDIRECT, SPECIAL, INCIDENTAL, AND/OR CONSEQUENTIAL DAMAGES
ARISING OUT OF THIS AGREEMENT OR USE OF THE TRAINING COURSE,
HOWEVER CAUSED, ON ANY THEORY OF LIABILITY, AND WHETHER OR NOT
ESRI OR ITS LICENSOR(S) HAVE BEEN ADVISED OF THE POSSIBILITY OF SUCH
DAMAGE. THESE LIMITATIONS SHALL APPLY NOTWITHSTANDING ANY
FAILURE OF ESSENTIAL PURPOSE OF ANY LIMITED REMEDY.
No Implied Waivers: No failure or delay by Esri or its licensor(s) in enforcing any right or
remedy under this Agreement shall be construed as a waiver of any future or other exercise of
such right or remedy by Esri or its licensor(s).
Order for Precedence: This Agreement shall take precedence over the terms and conditions of
any purchase order or other document, except as required by law or regulation.
Export Regulation: Licensee acknowledges that the Training Course and all underlying
information or technology may not be exported or re-exported into any country to which the
U.S. has embargoed goods, or to anyone on the U.S. Treasury Department's list of Specially
Designated Nationals, or to the U.S. Commerce Department's Table of Deny Orders. Licensee
shall not export the Training Course or any underlying information or technology to any facility
in violation of these or other applicable laws and regulations. Licensee represents and warrants
that it is not a national or resident of, or located in or under the control of, any country subject
to such U.S. export controls.
Severability: If any provision(s) of this Agreement shall be held to be invalid, illegal, or
unenforceable by a court or other tribunal of competent jurisdiction, the validity, legality, and
enforceability of the remaining provisions shall not in any way be affected or impaired thereby.
Governing Law: This Agreement, entered into in the County of San Bernardino, shall be
construed and enforced in accordance with and be governed by the laws of the United States of
America and the State of California without reference to conflict of laws principles.
Entire Agreement: The parties agree that this Agreement constitutes the sole and entire
agreement of the parties as to the matter set forth herein and supersedes any previous
agreements, understandings, and arrangements between the parties relating hereto.