an introduction to python for gis specialists and data managers n.
Skip this Video
Loading SlideShow in 5 Seconds..
An Introduction to Python for GIS Specialists and Data Managers PowerPoint Presentation
Download Presentation
An Introduction to Python for GIS Specialists and Data Managers

Loading in 2 Seconds...

play fullscreen
1 / 42

An Introduction to Python for GIS Specialists and Data Managers - PowerPoint PPT Presentation

  • Uploaded on

An Introduction to Python for GIS Specialists and Data Managers. Jacob Morgan Brent Frakes National Park Service Fort Collins, CO April, 2008. Session Goals. Overview of Python See power of the language Understand basic syntax References to other sources

I am the owner, or an agent authorized to act on behalf of the owner, of the copyrighted work described.
Download Presentation

PowerPoint Slideshow about 'An Introduction to Python for GIS Specialists and Data Managers' - marigold

An Image/Link below is provided (as is) to download presentation

Download Policy: Content on the Website is provided to you AS IS for your information and personal use and may not be sold / licensed / shared on other websites without getting consent from its author.While downloading, if for some reason you are not able to download a presentation, the publisher may have deleted the file from their server.

- - - - - - - - - - - - - - - - - - - - - - - - - - E N D - - - - - - - - - - - - - - - - - - - - - - - - - -
Presentation Transcript
an introduction to python for gis specialists and data managers

An Introduction to Pythonfor GIS Specialists and Data Managers

Jacob Morgan

Brent FrakesNational Park ServiceFort Collins, COApril, 2008

session goals
Session Goals
  • Overview of Python
  • See power of the language
  • Understand basic syntax
  • References to other sources
  • Too little time to really cover everything
  • One: Basic Python
  • Two: Using the ESRI Geoprocessor
  • Three: Formatting Data and Python Scripting
  • Each one hour
  • Examples and practice
session 1 overview
Session 1: Overview
  • Scripts and the Debugger
  • Commenting
  • Data Types
  • Operators
  • Decisions and Loops
  • File Handling
  • Modules, Functions and Classes
scripts and the debugger
Scripts and the Debugger
  • General Setup and Notes
    • All code is text-based (*.py extension)
    • Once compiled, a new file will have a *.pyc extension.
    • Python is VERY picky about indentation
    • Python is case sensitive
  • IDLE
    • Free
    • GUI interface for development
    • Compiler included with ArcGIS
    • Provides debugging but doesn't allow for breakpoints
  • Pythonwin
    • Free
    • GUI interface for development
    • Good debugger with breakpoints
scripts and the debugger1
Scripts and the Debugger
  • Exercise
    • type at the prompt >>'hello world'
    • type at the prompt >>print 'hello world'
    • Run a script with the following code:
      • print 'hello world'
  • Why?
    • Make your code understandable to you and others
    • How to use code
    • Why code was written
    • Debugging (comment out parts of script)
  • Ways to Comment
    • Single Line: use the pound (#) sign before the comment text.

# single line commented text

    • Multiple Lines: use triple quotes before and after a text block.

“ “ “

These two lines of text

Are being commented out

“ “ “

  • Add both types of comments to your script
data types
Data Types
  • Strings
  • Numeric
  • Lists
  • Tuples
  • An ordered collection of characters used to represent text-based information
  • Common String Literals and Operations
    • strNull = ' ' #empty string
    • str1 = "metadata" #double-quotes
    • str2 = '.xml' #single quotes
    • str3 = str1 + str2 #concatenate
    • strNull*100 #repeat
    • str2.upper() #string method call
    • str1[0:2] #indexing
    • str1 = str1+str2 #strings can't be modified

but can be reassigned

  • Special Strings
    • \n #newline
    • \t #horizontal tab
    • \\ #backslash
  • Type the following


>>>b = 'World'

>>> a+b

>>> (a+b)*10

>>> a[0:1]

>>> a[-4:-1]



  • Add two strings
  • Try using the two other string methods
numeric types
Numeric Types
  • Four types:
    • Integers
      • Numeric type providing a container for whole numbers. Plain integers are precise up to 32 bits (dependant on platform and compiler).
    • Floating Point Numbers
      • Numbers those with a decimal component. These are called floating point since the decimal point can be positioned anywhere in the digit string by a signed integer exponent-
    • Long Integers
    • Complex Numbers
numeric considerations
Numeric Considerations
  • Integer calculations yield integers (including division!)
  • Floating point calculations yield floating points
  • The constructors int(), long(), float(), and complex() can be used to produce numbers of a specific type. However, converting numbers between types may result in rounding or truncating digits.
numeric types exercises
Numeric Types - Exercises

>> 1 # 1

>>a= 2 #set value to 2

>>b= 3


>>b/a #still an integer

>>value = "10" #not an integer

>>c = 1.27 #floating point



>>d = int(c) #rounding

  • An ordered collections of arbitrary objects
  • Fully indexed
  • Variable in length, heterogenous, and arbitrarily nestable
  • Can be altered
  • Always in brackets
  • Aka Arrays!
list examples
List - Examples

d = [] # empty list

d = [1,2,3] #list of three integers

d = [1,2,"3"] #two integers and a string

d[0] #first element

d = [[1,2, 3],[3,4, 5]] #3 by 3 array

len(d) # 2

len(d[0]) #3

lists exercises
Lists - Exercises

>>L1 = [1,2,3,4,5,6]


>> L1 [0]

>> L1.pop() #remove last element from stack

>> L1 #6 is removed

>> L1 [0:2] #index 0-2

>> L1 [-1] #index from end of list

>>L2 = [5,6,7]

>> L1.append(L2) #insert a new list

>> L1

>> L1.extend(L2) #extend the current list

>> L1

  • Operators compute a value when presented with a string or number
  • Common Operators include:
    • x=y #assign
    • x==y #true or false
    • x < y #True or false
    • x<=y #True or false
    • x>y #True or false
    • x*y, x/y, x+y, x-y #Basic math
    • x[1] #index
    • x[1:10] #slice
    • x or y #y evaluated only if x is false
    • x and y #y is evaluated only if x is true
operators exercises
Operators - Exercises
  • >>>x = 5
  • >>>y = 6
  • >>> x < y
  • >>> x > y
  • >>> x < y or y > 7
  • >>> x < y and y > 7
controlling flow
Controlling Flow
  • Decisions/Conditionals are statements that determine if a series of conditions is true.
  • Most common
    • if
    • for
    • while
decisions conditionals

if condition:


elif condition:


else condition:


if condition example
“if” Condition Example

x = 15

if x > 5 and x < 10 :

print “The value is between 5 and 10”


print “The value is not between 5 and 10”

if condition exercise
“if” Condition - Exercise

>>>x = 7

>>>if x > 5 and x < 10 :

… print “The value is between 5 and 10”

for loop
“for” loop
  • Supports repeated execution of a statement, or block of statements, controlled by an iterable express

for target in iterable:


else: #optional on normal termination


for examples
“for” Examples

for x in range (1,30,2):

print x

for letter in “hello world”:

print letter

infile = open (“dataset.txt”,”r”)

for line in infile:

print line

for exercises
For Exercises

>>>for x in range(1,20):

… if x%2 == 0:

… print x, “ is even”

>>>import glob

>>>files = glob.glob(“*.*”)

>>>for file in files:

… print file

while loop
“while” loop
  • allows looping to occur only while a specified condition is true. WHILE evaluates the condition each time the loop completes and terminates the loop when the condition evaluates to false

while expression:


else: #optional for normal termination


while examples
While Examples

x = 100

while x>0:

x = x/2

print x

while exercise
While Exercise

>>>x = 20

>>>y = 0

>>>while x>=y:

… print y

… y += 2

file handling
File Handling
  • Ways to open, read, write, and close files

File2read = open (filename, mode = 'r')

filename - string containing filename and extension (e.g., 'metadata.xml')

file modes - indicates how to read or write the file

'r' - file must already exist and is read only

'w' - creates a new file for writing. Overwrites any existing filename

'a' - Write only mode. If file already exists, information is appended.

'r+' - File must already exist and is opened for both reading and writing.

'w+' - New file is created. Open for reading and writing.

'a+' - File open for reading and writing. If file already exists, data is appended.

useful file methods
Useful File Methods
  • - reads up to the end of file and returns it as a string.
  • file.readline() - reads one line from file (up to the '\n') and returns a string
  •, how = 0) - Move to a position in the file. 'How' is the reference point for moving (0 = start of file, 1 = current position; 2 = end of file).
  • file.write() - Writes a string to a file
  • file.writelines(line) - writes a line to a file
  • file.close() - # must be closed for it to be unlocked by Windows
file examples
File Examples
  • infile = open(“d.txt”, 'r')
  • data = #the string data is assigned the file contents
  • outfile = open(“e.txt”,'w') # assign outfile to the file object for writing
  • outfile.write(data) # write the contents to the file
  • infile.close()
  • outfile.close()
file exercises
File Exercises

>>>filename = “C:\\temp\\test.txt”

>>>outfile = open (filename ,’w’)

>>>outfile.write(“hello world”)


>>>infile = open(filename ,’r’)

>>>data =

>>>print filename, “-”, data


modules functions and classes
Modules, Functions, and Classes
  • Module
    • Single Python file
    • Provides definitions of functions, variables or classes
    • Corresponds to a specific thema (e.g., read, edit, and write zipfiles)
    • Composed of functions and/or classes. Functions can be stand-alone or are part of a class. Whether a function or class, both accomplish tasks.
standard modules
Standard Modules
  • Supported by Python - integral to many applications
  • Index can be found at:
  • Importing is simple:
  • >>import module
  • (e.g., import os)
accessing functions
Accessing Functions

import module



import os

os.getcwd() #get current directory

import glob

glob.glob(“*.py”) #get a list of all files with the .py extension

instantiating classes
Instantiating Classes

import module

instance = module.class(arguments)



Import gzip #import gzip module

Zipfile = gzip.GzipFile(“”) #instantiate GzipFile class

files = #Read zipfile and assign it to the files string

getting documentation about modules
Getting Documentation About Modules

dir() – List of available functions and methods

module.__doc__ - module documentation

module.function.__doc__ - function/method documentation


import os



third party modules
Third Party Modules
  • Many others have developed modules and posted them to the Python Package Index (

>>>import os



>>>import shutil