Sunteți pe pagina 1din 12

Python Programming for Arcgis 2

Daniel Sheehan
dsheehan@mit.edu, gishelp@mit.edu
9:30-12:30
February 1, 2013

This class was originally developed by David


Quinn and taught by David and Daniel in IAP
2010 and 2011.

Outline
More data types
Python functions
Accessing Attribute Tables

Lists = []
An ordered set of elements enclosed in square brackets.
Zero based (first element is accessed by typing list[0]).
# This is a list []
animals = [ 'dog ' , ' cat ' , 'horse ' , ' seal ' ]
Print animals[3]

Animals.append(owl)
Lists are mutable

Tuples = ()
Zero base (first element of a non-empty tuple is
always tuple[0]
# This is a tuple
Countries = (Costa Rica, India, Abu Dhabi)

# You cannot change a tuple (immutable)

String processing slicing a string


# slicing a string
Name = Massachusetts
#Fenceposts
Name[1:2]

Name[:4]

Example Function 1
# Python uses dynamic typing (type is set when
a variable is assigned or argument is passed)
def example(argument):
# Print the passed argument
print argument
# default return is none for a function

Example Function 2
# Function will give an error if argument is not a
number
# Save this file as example.py
def test_value(number):
# Add documentation here
number += 8
return number

Import example.py - DIY


# Importing a script
import example
# get new number from function
Answer = example.test_value(15)
print answer

Exercise 1: Function to return shapefile


name
Take in full file path string:
C:\\usertemp\\testshape.shp
Return shapefile name:
center.shp
Should work for any full file path string, not one
case. You should have a second .py file to call
the function.
Examine python documentation http://python.org;
in particular string.split()

Accessing the Attribute Table


def main(shapefile):
# returns the length of all line segments in an attribute table
import arcpy, os
sumLength = 0.0
testColumn = 'ROUTE_NUM'
testCondition = 'I95'
try:
with arcpy.da.SearchCursor(shapefile, ("DIST_MILES")) as
cursor:
for row in cursor:
sumLength += row[0]
print str(row[0])
del cursor
except:
return -9999
return sumLength

Exercise 2
Call the function in the previous slide (called
accessAT.py) from a .py file. You should submit
a full path to the shapefile
(C:\\...\\interstateHighways.shp) as the
argument to the function. Once this works, add
a where clause to the searchCursor function call to
find only records for I95. You will need to see the
help page for the function, especially Example 4.
Be careful with \I95\.

Exercise 3
Adapt the script in Exercise 2 to:
Convert interstateHighways.shp to points
Write out the ROUTE_NUM, SHAPE@X,
SHAPE@Y for I90, then I93, then I95
You can add arguments to the accessAT function
to pass both the shapefile name and the route
you are working on.

S-ar putea să vă placă și