Python Programming for Arcgis 1 Daniel Sheehan dsheehan@mit.edu, gishelp@mit.edu 9:30AM-12:30PM January 14, 2015 This class was originally developed by David Quinn and taught by David and Daniel in IAP 2010 and 2011.
Arcgis 10.2.2 and Python • You need a normal install of Arcgis 10.2.2. This install includes Python 2.7 and includes the IDLE interface, which we will use. • Other installs of Pythons will not have the ‘arcpy’ module and will not work.
Download data for workshop • http://web.mit.edu/dsheehan/www/ dataForPythonIAP2015.zip • http://web.mit.edu/dsheehan/www/ PythonProgrammingforArcgis.pdf
Goals for the workshop • Learning enough Python to – Access Arcgis commands through Python – Access individual records from attribute table – Acccess individual geometries for use in geoprocessing • Develop the ability to record and document your geoprocessing
Outline • Introduction to Python and Arcgis • Programming Principles and Modules • Model Builder • Reading and Writing data
Schedule Working with Python and geoprocessing tools today, working with attribute tables and individual geometries tomorrow
Python Python is a language that lets you work more quickly and integrate your systems more effectively 1 Documentation at http://docs.python.org and look for Python 2.7 (used in Arcgis 10.2.2) 1 http://www.python.org
Python + Arcgis • Python can interact with Arcgis and be used to repeat many types of analyses. • Why Python? • It is an integral part of Arcgis • Easy to read syntax • Large user community • Useful for scripts to control other programs
How does Python work with Arcgis • At Arcgis 10.2.2 – Fully integrated into Arcgis – Largely Geoprocessing functions • Automated mapping is not possible, yet
Logistics • We will be using the IDLE programming environment • Windows: START -> Programs -> Arcgis -> Python 2.7 -> IDLE • We are using Arcgis 10.2.2 on lab computers and assume that you are using 10.2.2 if you are using your own laptop
Learn by doing • Try every line of code in the slides • Create a new file for each different slide to create a record for yourself (optional) • Use the Python Help and Arcgis Help and ask questions
Programming concepts • Variables • Control Structures (IF statements and FOR loops) • Functions Python is case sensitive and reads whitespace for defining programming blocks – use space bar, not tabs.
The Print Function and Strings # this is a comment print “hello world” “”” Alternative Commenting Style “””
The Print function and Strings # this is a comment print (“hello world”) # this is a variable that contains a string name = “Daniel” print (name)
Integers and Floats # declare variables int_sample = 10 float_sample = 10.0 # printing variables # cast non-string variable as a string using str() print “The value of this integer is: “ + str(int_sample) print “The value of this float is: “ + str(float_sample)
if statement x = 2 # Condition checks if statement is true if x == 1: print ‘x is 1!’
if / elif / else statement x = 2 # Condition checks if statement is true if x == 1: print ‘x is 1!’ elif x == 2: print ‘x is 2!’ else: print ‘x is not known’
for loop for i in range(3): # convention is to use 4 spaces to indent # python reads whitespace at the beginning of a line print i Python, like most programming languages, uses arrrays that are zero based.
while loop # define j j = 1 # ‘while’ less than some condition while j < 3: print j # increment j j += 1
Three ways to access a folder # Accessing a folder path = “C:folderName” path = “C:/folderName/” path = r”C:folderName”
Importing Modules Use the import command: # count the number of files in a directory import os path = “c:...” files = os.listdir(path) print len(files) A module is a list of Python programs that can be accessed. Commonly used modules are os, sys, glob.
glob import glob # use the glob module path = “C:UsersdsheehandesktopPython2015current ” # loop through all files ListOfFiles = glob.glob(path + “*”) for i in ListOfFiles: print i Try replacing ‘*’ with ‘*.shp’
Importing the Arcgis module At 10.2.2 import arcpy
Exercise 1: Reading folder contents • Download zip file from http://web.mit.edu/dsheehan/ dataForPythonIAP2015.zip and unzip • Using the glob module, print out: – a list of all of the files – a list of shapefiles
Model Builder
Exercise 2: ModelBuilder Using ModelBuilder: • Buffer interstateHighways.shp (500 meters) – Units of data is meters • Clip schools.shp with buffer • Export model as ‘Python’
Catching exceptions try: <your code> except: print arcpy.GetMessages() raise
Overwriting files • from arcpy import env • env.overwriteOutput = True
Exercise 3: Convert ModelBuilder Code into a loop • Using the code from ModelBuilder • Iterate through a loop 5 times, buffering 500 meters, 1000, etc meters • Intersect cambridgeSchools.shp with buffer and make 5 new pairs of shapefiles
Writing to a text file # Create a file (‘w’ means create a new file, ‘a’ appends to an existing file, will create it if it doesn’t already exist) f = open(“C:usersdsheehantest.txt”, ‘w’) # Write to a file f.write(“Contents of file” + “n”) f.flush() # flushes buffer f.close() # closes file
Exercise 4: File Manipulation Create a folder called “temp_folder”: • Make 5 text files in this folder called File1.txt, File2.txt, etc. • Write a string in each file

Python Programming for ArcGIS: Part I

  • 1.
    Python Programming forArcgis 1 Daniel Sheehan dsheehan@mit.edu, gishelp@mit.edu 9:30AM-12:30PM January 14, 2015 This class was originally developed by David Quinn and taught by David and Daniel in IAP 2010 and 2011.
  • 2.
    Arcgis 10.2.2 andPython • You need a normal install of Arcgis 10.2.2. This install includes Python 2.7 and includes the IDLE interface, which we will use. • Other installs of Pythons will not have the ‘arcpy’ module and will not work.
  • 3.
    Download data forworkshop • http://web.mit.edu/dsheehan/www/ dataForPythonIAP2015.zip • http://web.mit.edu/dsheehan/www/ PythonProgrammingforArcgis.pdf
  • 4.
    Goals for theworkshop • Learning enough Python to – Access Arcgis commands through Python – Access individual records from attribute table – Acccess individual geometries for use in geoprocessing • Develop the ability to record and document your geoprocessing
  • 5.
    Outline • Introduction toPython and Arcgis • Programming Principles and Modules • Model Builder • Reading and Writing data
  • 6.
    Schedule Working with Pythonand geoprocessing tools today, working with attribute tables and individual geometries tomorrow
  • 7.
    Python Python is alanguage that lets you work more quickly and integrate your systems more effectively 1 Documentation at http://docs.python.org and look for Python 2.7 (used in Arcgis 10.2.2) 1 http://www.python.org
  • 8.
    Python + Arcgis •Python can interact with Arcgis and be used to repeat many types of analyses. • Why Python? • It is an integral part of Arcgis • Easy to read syntax • Large user community • Useful for scripts to control other programs
  • 9.
    How does Pythonwork with Arcgis • At Arcgis 10.2.2 – Fully integrated into Arcgis – Largely Geoprocessing functions • Automated mapping is not possible, yet
  • 10.
    Logistics • We willbe using the IDLE programming environment • Windows: START -> Programs -> Arcgis -> Python 2.7 -> IDLE • We are using Arcgis 10.2.2 on lab computers and assume that you are using 10.2.2 if you are using your own laptop
  • 11.
    Learn by doing •Try every line of code in the slides • Create a new file for each different slide to create a record for yourself (optional) • Use the Python Help and Arcgis Help and ask questions
  • 12.
    Programming concepts • Variables •Control Structures (IF statements and FOR loops) • Functions Python is case sensitive and reads whitespace for defining programming blocks – use space bar, not tabs.
  • 13.
    The Print Functionand Strings # this is a comment print “hello world” “”” Alternative Commenting Style “””
  • 14.
    The Print functionand Strings # this is a comment print (“hello world”) # this is a variable that contains a string name = “Daniel” print (name)
  • 15.
    Integers and Floats #declare variables int_sample = 10 float_sample = 10.0 # printing variables # cast non-string variable as a string using str() print “The value of this integer is: “ + str(int_sample) print “The value of this float is: “ + str(float_sample)
  • 16.
    if statement x =2 # Condition checks if statement is true if x == 1: print ‘x is 1!’
  • 17.
    if / elif/ else statement x = 2 # Condition checks if statement is true if x == 1: print ‘x is 1!’ elif x == 2: print ‘x is 2!’ else: print ‘x is not known’
  • 18.
    for loop for iin range(3): # convention is to use 4 spaces to indent # python reads whitespace at the beginning of a line print i Python, like most programming languages, uses arrrays that are zero based.
  • 19.
    while loop # definej j = 1 # ‘while’ less than some condition while j < 3: print j # increment j j += 1
  • 20.
    Three ways toaccess a folder # Accessing a folder path = “C:folderName” path = “C:/folderName/” path = r”C:folderName”
  • 21.
    Importing Modules Use theimport command: # count the number of files in a directory import os path = “c:...” files = os.listdir(path) print len(files) A module is a list of Python programs that can be accessed. Commonly used modules are os, sys, glob.
  • 22.
    glob import glob #use the glob module path = “C:UsersdsheehandesktopPython2015current ” # loop through all files ListOfFiles = glob.glob(path + “*”) for i in ListOfFiles: print i Try replacing ‘*’ with ‘*.shp’
  • 23.
    Importing the Arcgismodule At 10.2.2 import arcpy
  • 24.
    Exercise 1: Readingfolder contents • Download zip file from http://web.mit.edu/dsheehan/ dataForPythonIAP2015.zip and unzip • Using the glob module, print out: – a list of all of the files – a list of shapefiles
  • 25.
  • 26.
    Exercise 2: ModelBuilder UsingModelBuilder: • Buffer interstateHighways.shp (500 meters) – Units of data is meters • Clip schools.shp with buffer • Export model as ‘Python’
  • 27.
  • 28.
    Overwriting files • fromarcpy import env • env.overwriteOutput = True
  • 29.
    Exercise 3: ConvertModelBuilder Code into a loop • Using the code from ModelBuilder • Iterate through a loop 5 times, buffering 500 meters, 1000, etc meters • Intersect cambridgeSchools.shp with buffer and make 5 new pairs of shapefiles
  • 30.
    Writing to atext file # Create a file (‘w’ means create a new file, ‘a’ appends to an existing file, will create it if it doesn’t already exist) f = open(“C:usersdsheehantest.txt”, ‘w’) # Write to a file f.write(“Contents of file” + “n”) f.flush() # flushes buffer f.close() # closes file
  • 31.
    Exercise 4: FileManipulation Create a folder called “temp_folder”: • Make 5 text files in this folder called File1.txt, File2.txt, etc. • Write a string in each file