SlideShare a Scribd company logo
>>> Python and GIS: …  Beyond ModelBuilder …  and PythonWin Chad Cooper Southwestern Energy Company
>>> What we'll cover > Lists, lists, lists > Code examples > 3 rd  party modules > Editors/IDEs > Python references > This presentation/code online! Code in orange Pseudocode in blue Output/results in green
>>> Love the list > List: Array of object references - Huh?  or  Ordered collection of arbitrary objects list1 = [0,1,2,3] list2 = ['zero','one','two','three'] list3 = [0,'zero',1,'one',2,'two',3,'three'] > Ordered  list2.sort()  list2.sort(reverse=True) ['one','three',...]  ['zero','two',...] > Mutable  list1.append(4)  list1.reverse() [0,1,2,3,4]  [4,3,2,1,0]
>>> Keep lovin' the list > Iterable  for l in list3 0 zero ... > Membership  3 in list3   --> True > Nestable - 2D array/matrix list4 = [[0,1,2],  [3,4,5], [6,7,8]] > Access by index - zero-based  list4[1]  list4[1][2] [3,4,5]  5
>>> Process a text file 1  import csv, arcgisscripting 2  gp = arcgisscripting.create() 3  rows = gp.InsertCursor('C:/database.gdb/table') 4  fields = ['slat','slon','spud'] 5  reader = csv.reader(open('C:/file.csv','rb')) 6  for line in reader: 7   t = 0 8   row = rows.NewRow() 9   for field in fields: 10   row.SetValue(field,line[t]) 11   t = t + 1 12   rows.InsertRow(row) CSV GDB table
>>> Databases:   MS SqlServer 1  import ceODBC 2  db = ceODBC.connect('DSN=Wells') 3  c = db.cursor() 4  c.execute('SELECT wellname, slat, slon \ 5   FROM wells WHERE wellid IN (1,2,3)') 6  for each in c.fetchall(): 7   print each [('DOE #1-18', 33.095599, -92.38563), ('SMITH #2-7', 35.10155, -91.48824), ('JOHN #11-13', 34.09130, -93.45256)]
>>> Databases:   IBM DB2 1  import ceODBC 2  db = ceODBC.connect('DSN=dsn;UID=uid;PWD=pwd') 3  c = db.cursor() 4  c.execute('SELECT wellname FROM wells') 5  for each in c.fetchmany(3): 6   print each [('DOE #1-18', 33.095599, -92.38563), ('SMITH #2-7', 35.10155, -91.48824), ('JOHN #11-13', 34.09130, -93.45256)]
>>> Sending email 1  import smtplib 2  server = smtplib.SMTP(email_server_ip) 3  msg = 'Eat more spam and eggs!' 4  server.sendmail('from@me.com', 5   'to@you.com', 6   msg) 7  server.quit() > Make sure port 25 is  unblocked!
>>> Download files > GNU wget - free CLI program > Retrieve using HTTP protocol > Build a URL such as: 'http://www.archive.org/download/ usgs_drg_ar_36094_a1/ o36094a1.tif' > Pass URL to wget, it fetches
>>> Download files 1  import os, shutil 2  wgetDir = 'C:/Program Files/wget/o' 3  quads =  4  [['36094a1','ELKINS','ar'],['36094a2','FAYETTEVILLE','ar']] 5  exts = ['tif', 'tfw', 'fgd'] 6  url = 'http://www.archive.org/download/' 7  home = 'C:/temp/quads/' 8  for quad in quads: 9   for ext in exts: 10   fullurl = url + 'usgs_drg_' + quad[2] + \ 11  '_' + quad[0][:5] + '_' + quad[0][5:] + \ 12   '/o' + quad[0] + '.' + ext 13   os.system('wget %s -o log.log' % (fullurl)) 14   # Move and rename --> AR_ELKINS_o35094h3.tif 15   shutil.move(wgetDir + quad[0] + '.' + ext,  16   home + quad[2].upper() + '_' + \ 17   quad[1].replace(' ','_') + \ 18   '_' + 'o' + quad[0] + '.' + ext)
>>> DB records --> FC 1  connect(dsn) 2  db.cursor() 3  execute(sql) 4  results = fetchall() 5  fields = [f1,f2,...] 6  rows = InsertCursor(table) 7  for r in results: 8   row = rows.NewRow() 9   row.SetValue(fields[i], r[i] 10   ... 11  if point data: 12   MakeXyEventLayer(table,x,y,layer) 13   CopyFeatures(layer,featureclass) 14  else: 15   AddJoin(layer,layerfield,table,tablefield) 16   CopyFeatures(layer,featureclass)
>>> 3 rd  party modules > pyExcelerator, xlrd - Excel > ceODBC, MySQLdb - databases > mxDateTime - date/time f(x)s > csv* - read/write csv files > geopy - geocode using 3 rd  party geocoders (Google, Yahoo, VE) > For fun: gdata (Google API), Flickr, digital photos (EXIF)  * in standard library
>>> Editors - Notepad > Basic - you write code, save
>>> Editors - Notepad2 > Line numbering, syntax coloring
>>> IDEs - SPE > IDE: Integrated development environment  > Tools > Debugger > Shell
>>> IDEs - IDLE > Ships with CPython distro
>>> Good references > http://www.python.org/doc > Module reference > Google group: comp.lang.python > Books: >  Python Cookbook   (recipes online) >  How to Think Like a Computer Scientist  (online) > ESRI gp scripting forum
>>> Further reading >  Python Magazine  - online print and pdf (for fee) >  The Python Papers  - pdf free  online >  Dive Into Python -  free online
[email_address] Presentation and code available at:  http://code.google.com/p/csvimporter ?

More Related Content

PDF
Productivity tips for developers
PPTX
CouchDB Day NYC 2017: MapReduce Views
PPTX
CouchDB Day NYC 2017: Full Text Search
PDF
Abusing Erlang compilation pipeline for Fun and Profit
ODT
Spatial script for MongoBoulder
PDF
Spatial script for my JS.Everywhere 2012
PDF
PHP 机智问答
PDF
Tests unitaires pour PostgreSQL avec pgTap
Productivity tips for developers
CouchDB Day NYC 2017: MapReduce Views
CouchDB Day NYC 2017: Full Text Search
Abusing Erlang compilation pipeline for Fun and Profit
Spatial script for MongoBoulder
Spatial script for my JS.Everywhere 2012
PHP 机智问答
Tests unitaires pour PostgreSQL avec pgTap

What's hot (19)

PDF
Shell Script to Extract IP Address, MAC Address Information
PDF
Bash Script Disk Space Utilization Report and EMail
PDF
File Space Usage Information and EMail Report - Shell Script
PDF
Spatial script for Spatial mongo for PHP and Zend
PDF
Git Tutorial Yang Yang
PPTX
Best Practices in Handling Performance Issues
PDF
Web Scrapping with Python
DOC
Quiz using C++
DOCX
computer project code ''payroll'' (based on datafile handling)
KEY
サイ本 文
PDF
Git for beginners
PPT
Qtp Scripts
PDF
Basicsof c make and git for a hello qt application
PDF
自己的JVM自己救: 解救 OOM 實務經驗談 (JCConf 2015)
PDF
Save JVM by Yourself: Real War Experiences of OOM
PDF
Pyspark
KEY
gunicorn introduction
Shell Script to Extract IP Address, MAC Address Information
Bash Script Disk Space Utilization Report and EMail
File Space Usage Information and EMail Report - Shell Script
Spatial script for Spatial mongo for PHP and Zend
Git Tutorial Yang Yang
Best Practices in Handling Performance Issues
Web Scrapping with Python
Quiz using C++
computer project code ''payroll'' (based on datafile handling)
サイ本 文
Git for beginners
Qtp Scripts
Basicsof c make and git for a hello qt application
自己的JVM自己救: 解救 OOM 實務經驗談 (JCConf 2015)
Save JVM by Yourself: Real War Experiences of OOM
Pyspark
gunicorn introduction
Ad

Viewers also liked (7)

PDF
Risk Management In Insolvency
PDF
The Insolvency and Bankruptcy Code 2015
PPSX
Insolvency and Bankruptcy Code, 2015 - Sandeep Jhunjhunwala FCA
PPTX
Bankruptcy Slide Show
PPT
Insolvency and bankruptcy code 2016
PPTX
Bankruptcy PPT
PPTX
Law of insolvency
Risk Management In Insolvency
The Insolvency and Bankruptcy Code 2015
Insolvency and Bankruptcy Code, 2015 - Sandeep Jhunjhunwala FCA
Bankruptcy Slide Show
Insolvency and bankruptcy code 2016
Bankruptcy PPT
Law of insolvency
Ad

Similar to Python And GIS - Beyond Modelbuilder And Pythonwin (20)

ODP
Use of django at jolt online v3
PPT
GeoScript - Spatial Capabilities for Scripting Languages
PPT
What's New in ZF 1.10
PPT
Writing Pluggable Software
DOCX
Computer science project work
PPTX
Groovy
PPT
Grails and Dojo
PPT
Introduction To Lamp
PDF
Python and sysadmin I
PDF
Танки_в_Лунапарке: нагрузочное_тестирование_в_Яндексе
PPT
Arcgis 10中的python
PPTX
C to perl binding
PPT
루비가 얼랭에 빠진 날
PDF
Osol Pgsql
PPT
11 Things About 11gr2
PPT
Introduction to Assembly Language
PPTX
PPT
Web Scraper Shibuya.pm tech talk #8
ODP
perl usage at database applications
PPT
Rapid and Scalable Development with MongoDB, PyMongo, and Ming
Use of django at jolt online v3
GeoScript - Spatial Capabilities for Scripting Languages
What's New in ZF 1.10
Writing Pluggable Software
Computer science project work
Groovy
Grails and Dojo
Introduction To Lamp
Python and sysadmin I
Танки_в_Лунапарке: нагрузочное_тестирование_в_Яндексе
Arcgis 10中的python
C to perl binding
루비가 얼랭에 빠진 날
Osol Pgsql
11 Things About 11gr2
Introduction to Assembly Language
Web Scraper Shibuya.pm tech talk #8
perl usage at database applications
Rapid and Scalable Development with MongoDB, PyMongo, and Ming

More from Chad Cooper (7)

PPTX
VIESORE - Visual Impact Evaluation System for Offshore Renewable Energy
PDF
Implementation of a geographic information systems (GIS)-based system to eval...
PPTX
VIESORE: Visual Impact Evaluation System for Offshore Renewable Energy
PPTX
Advanced geoprocessing with Python
PDF
Reading and writing spatial data for the non-spatial programmer
PPTX
IPAS: An ArcGIS Server-based framework for oil and gas E and P decision support
PPT
Water resources and hydrochemistry of the Alluvial and Sparta aquifers of the...
VIESORE - Visual Impact Evaluation System for Offshore Renewable Energy
Implementation of a geographic information systems (GIS)-based system to eval...
VIESORE: Visual Impact Evaluation System for Offshore Renewable Energy
Advanced geoprocessing with Python
Reading and writing spatial data for the non-spatial programmer
IPAS: An ArcGIS Server-based framework for oil and gas E and P decision support
Water resources and hydrochemistry of the Alluvial and Sparta aquifers of the...

Recently uploaded (20)

PPTX
20250228 LYD VKU AI Blended-Learning.pptx
PDF
Review of recent advances in non-invasive hemoglobin estimation
PDF
Spectral efficient network and resource selection model in 5G networks
PDF
TokAI - TikTok AI Agent : The First AI Application That Analyzes 10,000+ Vira...
PDF
Encapsulation theory and applications.pdf
PDF
Chapter 3 Spatial Domain Image Processing.pdf
PPTX
Big Data Technologies - Introduction.pptx
PDF
Advanced methodologies resolving dimensionality complications for autism neur...
PDF
CIFDAQ's Market Insight: SEC Turns Pro Crypto
DOCX
The AUB Centre for AI in Media Proposal.docx
PPTX
VMware vSphere Foundation How to Sell Presentation-Ver1.4-2-14-2024.pptx
PPT
Teaching material agriculture food technology
PDF
Machine learning based COVID-19 study performance prediction
PPTX
Effective Security Operations Center (SOC) A Modern, Strategic, and Threat-In...
PDF
NewMind AI Monthly Chronicles - July 2025
PDF
Modernizing your data center with Dell and AMD
PDF
NewMind AI Weekly Chronicles - August'25 Week I
PDF
Mobile App Security Testing_ A Comprehensive Guide.pdf
PPTX
KOM of Painting work and Equipment Insulation REV00 update 25-dec.pptx
PDF
Per capita expenditure prediction using model stacking based on satellite ima...
20250228 LYD VKU AI Blended-Learning.pptx
Review of recent advances in non-invasive hemoglobin estimation
Spectral efficient network and resource selection model in 5G networks
TokAI - TikTok AI Agent : The First AI Application That Analyzes 10,000+ Vira...
Encapsulation theory and applications.pdf
Chapter 3 Spatial Domain Image Processing.pdf
Big Data Technologies - Introduction.pptx
Advanced methodologies resolving dimensionality complications for autism neur...
CIFDAQ's Market Insight: SEC Turns Pro Crypto
The AUB Centre for AI in Media Proposal.docx
VMware vSphere Foundation How to Sell Presentation-Ver1.4-2-14-2024.pptx
Teaching material agriculture food technology
Machine learning based COVID-19 study performance prediction
Effective Security Operations Center (SOC) A Modern, Strategic, and Threat-In...
NewMind AI Monthly Chronicles - July 2025
Modernizing your data center with Dell and AMD
NewMind AI Weekly Chronicles - August'25 Week I
Mobile App Security Testing_ A Comprehensive Guide.pdf
KOM of Painting work and Equipment Insulation REV00 update 25-dec.pptx
Per capita expenditure prediction using model stacking based on satellite ima...

Python And GIS - Beyond Modelbuilder And Pythonwin

  • 1. >>> Python and GIS: … Beyond ModelBuilder … and PythonWin Chad Cooper Southwestern Energy Company
  • 2. >>> What we'll cover > Lists, lists, lists > Code examples > 3 rd party modules > Editors/IDEs > Python references > This presentation/code online! Code in orange Pseudocode in blue Output/results in green
  • 3. >>> Love the list > List: Array of object references - Huh? or Ordered collection of arbitrary objects list1 = [0,1,2,3] list2 = ['zero','one','two','three'] list3 = [0,'zero',1,'one',2,'two',3,'three'] > Ordered list2.sort() list2.sort(reverse=True) ['one','three',...] ['zero','two',...] > Mutable list1.append(4) list1.reverse() [0,1,2,3,4] [4,3,2,1,0]
  • 4. >>> Keep lovin' the list > Iterable for l in list3 0 zero ... > Membership 3 in list3 --> True > Nestable - 2D array/matrix list4 = [[0,1,2], [3,4,5], [6,7,8]] > Access by index - zero-based list4[1] list4[1][2] [3,4,5] 5
  • 5. >>> Process a text file 1 import csv, arcgisscripting 2 gp = arcgisscripting.create() 3 rows = gp.InsertCursor('C:/database.gdb/table') 4 fields = ['slat','slon','spud'] 5 reader = csv.reader(open('C:/file.csv','rb')) 6 for line in reader: 7 t = 0 8 row = rows.NewRow() 9 for field in fields: 10 row.SetValue(field,line[t]) 11 t = t + 1 12 rows.InsertRow(row) CSV GDB table
  • 6. >>> Databases: MS SqlServer 1 import ceODBC 2 db = ceODBC.connect('DSN=Wells') 3 c = db.cursor() 4 c.execute('SELECT wellname, slat, slon \ 5 FROM wells WHERE wellid IN (1,2,3)') 6 for each in c.fetchall(): 7 print each [('DOE #1-18', 33.095599, -92.38563), ('SMITH #2-7', 35.10155, -91.48824), ('JOHN #11-13', 34.09130, -93.45256)]
  • 7. >>> Databases: IBM DB2 1 import ceODBC 2 db = ceODBC.connect('DSN=dsn;UID=uid;PWD=pwd') 3 c = db.cursor() 4 c.execute('SELECT wellname FROM wells') 5 for each in c.fetchmany(3): 6 print each [('DOE #1-18', 33.095599, -92.38563), ('SMITH #2-7', 35.10155, -91.48824), ('JOHN #11-13', 34.09130, -93.45256)]
  • 8. >>> Sending email 1 import smtplib 2 server = smtplib.SMTP(email_server_ip) 3 msg = 'Eat more spam and eggs!' 4 server.sendmail('from@me.com', 5 'to@you.com', 6 msg) 7 server.quit() > Make sure port 25 is unblocked!
  • 9. >>> Download files > GNU wget - free CLI program > Retrieve using HTTP protocol > Build a URL such as: 'http://www.archive.org/download/ usgs_drg_ar_36094_a1/ o36094a1.tif' > Pass URL to wget, it fetches
  • 10. >>> Download files 1 import os, shutil 2 wgetDir = 'C:/Program Files/wget/o' 3 quads = 4 [['36094a1','ELKINS','ar'],['36094a2','FAYETTEVILLE','ar']] 5 exts = ['tif', 'tfw', 'fgd'] 6 url = 'http://www.archive.org/download/' 7 home = 'C:/temp/quads/' 8 for quad in quads: 9 for ext in exts: 10 fullurl = url + 'usgs_drg_' + quad[2] + \ 11 '_' + quad[0][:5] + '_' + quad[0][5:] + \ 12 '/o' + quad[0] + '.' + ext 13 os.system('wget %s -o log.log' % (fullurl)) 14 # Move and rename --> AR_ELKINS_o35094h3.tif 15 shutil.move(wgetDir + quad[0] + '.' + ext, 16 home + quad[2].upper() + '_' + \ 17 quad[1].replace(' ','_') + \ 18 '_' + 'o' + quad[0] + '.' + ext)
  • 11. >>> DB records --> FC 1 connect(dsn) 2 db.cursor() 3 execute(sql) 4 results = fetchall() 5 fields = [f1,f2,...] 6 rows = InsertCursor(table) 7 for r in results: 8 row = rows.NewRow() 9 row.SetValue(fields[i], r[i] 10 ... 11 if point data: 12 MakeXyEventLayer(table,x,y,layer) 13 CopyFeatures(layer,featureclass) 14 else: 15 AddJoin(layer,layerfield,table,tablefield) 16 CopyFeatures(layer,featureclass)
  • 12. >>> 3 rd party modules > pyExcelerator, xlrd - Excel > ceODBC, MySQLdb - databases > mxDateTime - date/time f(x)s > csv* - read/write csv files > geopy - geocode using 3 rd party geocoders (Google, Yahoo, VE) > For fun: gdata (Google API), Flickr, digital photos (EXIF) * in standard library
  • 13. >>> Editors - Notepad > Basic - you write code, save
  • 14. >>> Editors - Notepad2 > Line numbering, syntax coloring
  • 15. >>> IDEs - SPE > IDE: Integrated development environment > Tools > Debugger > Shell
  • 16. >>> IDEs - IDLE > Ships with CPython distro
  • 17. >>> Good references > http://www.python.org/doc > Module reference > Google group: comp.lang.python > Books: > Python Cookbook (recipes online) > How to Think Like a Computer Scientist (online) > ESRI gp scripting forum
  • 18. >>> Further reading > Python Magazine - online print and pdf (for fee) > The Python Papers - pdf free online > Dive Into Python - free online
  • 19. [email_address] Presentation and code available at: http://code.google.com/p/csvimporter ?