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 ?
Ad

Recommended

Productivity tips for developers
Productivity tips for developers
Sebastian Witowski
 
CouchDB Day NYC 2017: MapReduce Views
CouchDB Day NYC 2017: MapReduce Views
IBM Cloud Data Services
 
CouchDB Day NYC 2017: Full Text Search
CouchDB Day NYC 2017: Full Text Search
IBM Cloud Data Services
 
Abusing Erlang compilation pipeline for Fun and Profit
Abusing Erlang compilation pipeline for Fun and Profit
Wojciech Gawroński
 
Spatial script for MongoBoulder
Spatial script for MongoBoulder
Steven Pousty
 
Spatial script for my JS.Everywhere 2012
Spatial script for my JS.Everywhere 2012
Steven Pousty
 
PHP 机智问答
PHP 机智问答
Shengyou Fan
 
Tests unitaires pour PostgreSQL avec pgTap
Tests unitaires pour PostgreSQL avec pgTap
Rodolphe Quiédeville
 
Shell Script to Extract IP Address, MAC Address Information
Shell Script to Extract IP Address, MAC Address Information
VCP Muthukrishna
 
Bash Script Disk Space Utilization Report and EMail
Bash Script Disk Space Utilization Report and EMail
VCP Muthukrishna
 
File Space Usage Information and EMail Report - Shell Script
File Space Usage Information and EMail Report - Shell Script
VCP Muthukrishna
 
Spatial script for Spatial mongo for PHP and Zend
Spatial script for Spatial mongo for PHP and Zend
Steven Pousty
 
Git Tutorial Yang Yang
Git Tutorial Yang Yang
Yang Yang
 
Sol10
Sol10
University Of Lahore
 
Best Practices in Handling Performance Issues
Best Practices in Handling Performance Issues
Odoo
 
Web Scrapping with Python
Web Scrapping with Python
Miguel Miranda de Mattos
 
Quiz using C++
Quiz using C++
Sushil Mishra
 
computer project code ''payroll'' (based on datafile handling)
computer project code ''payroll'' (based on datafile handling)
Nitish Yadav
 
サイ本 文
サイ本 文
Takashi Takizawa
 
Git for beginners
Git for beginners
Vinh Nguyen
 
Qtp Scripts
Qtp Scripts
G.C Reddy
 
Sol7
Sol7
University Of Lahore
 
Basicsof c make and git for a hello qt application
Basicsof c make and git for a hello qt application
Dinesh Manajipet
 
自己的JVM自己救: 解救 OOM 實務經驗談 (JCConf 2015)
自己的JVM自己救: 解救 OOM 實務經驗談 (JCConf 2015)
Leon Chen
 
Save JVM by Yourself: Real War Experiences of OOM
Save JVM by Yourself: Real War Experiences of OOM
Leon Chen
 
Pyspark
Pyspark
Ajay Ohri
 
gunicorn introduction
gunicorn introduction
Adam Lowry
 
Risk Management In Insolvency
Risk Management In Insolvency
Andrei Burz-Pinzaru
 
The Insolvency and Bankruptcy Code 2015
The Insolvency and Bankruptcy Code 2015
Mukesh Chand
 
Insolvency and Bankruptcy Code, 2015 - Sandeep Jhunjhunwala FCA
Insolvency and Bankruptcy Code, 2015 - Sandeep Jhunjhunwala FCA
Sandeep Jhunjhunwala
 

More Related Content

What's hot (19)

Shell Script to Extract IP Address, MAC Address Information
Shell Script to Extract IP Address, MAC Address Information
VCP Muthukrishna
 
Bash Script Disk Space Utilization Report and EMail
Bash Script Disk Space Utilization Report and EMail
VCP Muthukrishna
 
File Space Usage Information and EMail Report - Shell Script
File Space Usage Information and EMail Report - Shell Script
VCP Muthukrishna
 
Spatial script for Spatial mongo for PHP and Zend
Spatial script for Spatial mongo for PHP and Zend
Steven Pousty
 
Git Tutorial Yang Yang
Git Tutorial Yang Yang
Yang Yang
 
Sol10
Sol10
University Of Lahore
 
Best Practices in Handling Performance Issues
Best Practices in Handling Performance Issues
Odoo
 
Web Scrapping with Python
Web Scrapping with Python
Miguel Miranda de Mattos
 
Quiz using C++
Quiz using C++
Sushil Mishra
 
computer project code ''payroll'' (based on datafile handling)
computer project code ''payroll'' (based on datafile handling)
Nitish Yadav
 
サイ本 文
サイ本 文
Takashi Takizawa
 
Git for beginners
Git for beginners
Vinh Nguyen
 
Qtp Scripts
Qtp Scripts
G.C Reddy
 
Sol7
Sol7
University Of Lahore
 
Basicsof c make and git for a hello qt application
Basicsof c make and git for a hello qt application
Dinesh Manajipet
 
自己的JVM自己救: 解救 OOM 實務經驗談 (JCConf 2015)
自己的JVM自己救: 解救 OOM 實務經驗談 (JCConf 2015)
Leon Chen
 
Save JVM by Yourself: Real War Experiences of OOM
Save JVM by Yourself: Real War Experiences of OOM
Leon Chen
 
Pyspark
Pyspark
Ajay Ohri
 
gunicorn introduction
gunicorn introduction
Adam Lowry
 
Shell Script to Extract IP Address, MAC Address Information
Shell Script to Extract IP Address, MAC Address Information
VCP Muthukrishna
 
Bash Script Disk Space Utilization Report and EMail
Bash Script Disk Space Utilization Report and EMail
VCP Muthukrishna
 
File Space Usage Information and EMail Report - Shell Script
File Space Usage Information and EMail Report - Shell Script
VCP Muthukrishna
 
Spatial script for Spatial mongo for PHP and Zend
Spatial script for Spatial mongo for PHP and Zend
Steven Pousty
 
Git Tutorial Yang Yang
Git Tutorial Yang Yang
Yang Yang
 
Best Practices in Handling Performance Issues
Best Practices in Handling Performance Issues
Odoo
 
computer project code ''payroll'' (based on datafile handling)
computer project code ''payroll'' (based on datafile handling)
Nitish Yadav
 
Git for beginners
Git for beginners
Vinh Nguyen
 
Basicsof c make and git for a hello qt application
Basicsof c make and git for a hello qt application
Dinesh Manajipet
 
自己的JVM自己救: 解救 OOM 實務經驗談 (JCConf 2015)
自己的JVM自己救: 解救 OOM 實務經驗談 (JCConf 2015)
Leon Chen
 
Save JVM by Yourself: Real War Experiences of OOM
Save JVM by Yourself: Real War Experiences of OOM
Leon Chen
 
gunicorn introduction
gunicorn introduction
Adam Lowry
 

Viewers also liked (7)

Risk Management In Insolvency
Risk Management In Insolvency
Andrei Burz-Pinzaru
 
The Insolvency and Bankruptcy Code 2015
The Insolvency and Bankruptcy Code 2015
Mukesh Chand
 
Insolvency and Bankruptcy Code, 2015 - Sandeep Jhunjhunwala FCA
Insolvency and Bankruptcy Code, 2015 - Sandeep Jhunjhunwala FCA
Sandeep Jhunjhunwala
 
Bankruptcy Slide Show
Bankruptcy Slide Show
dcwinton
 
Insolvency and bankruptcy code 2016
Insolvency and bankruptcy code 2016
Altacit Global
 
Bankruptcy PPT
Bankruptcy PPT
Anil Kaswan
 
Law of insolvency
Law of insolvency
Sumit Banerjee
 
The Insolvency and Bankruptcy Code 2015
The Insolvency and Bankruptcy Code 2015
Mukesh Chand
 
Insolvency and Bankruptcy Code, 2015 - Sandeep Jhunjhunwala FCA
Insolvency and Bankruptcy Code, 2015 - Sandeep Jhunjhunwala FCA
Sandeep Jhunjhunwala
 
Bankruptcy Slide Show
Bankruptcy Slide Show
dcwinton
 
Insolvency and bankruptcy code 2016
Insolvency and bankruptcy code 2016
Altacit Global
 
Ad

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

Advanced geoprocessing with Python
Advanced geoprocessing with Python
Chad Cooper
 
Reading and writing spatial data for the non-spatial programmer
Reading and writing spatial data for the non-spatial programmer
Chad Cooper
 
Python_Basics_CheatSheet for Python Engineers
Python_Basics_CheatSheet for Python Engineers
tareqbata1
 
Python Cheat Sheet 2.0.pdf
Python Cheat Sheet 2.0.pdf
Rahul Jain
 
PART 3: THE SCRIPTING COMPOSER AND PYTHON
PART 3: THE SCRIPTING COMPOSER AND PYTHON
Andrea Antonello
 
Python Workshop Part 2. LUG Maniapl
Python Workshop Part 2. LUG Maniapl
Ankur Shrivastava
 
Shrug2017 arcpy data_and_you
Shrug2017 arcpy data_and_you
SHRUG GIS
 
Python first day
Python first day
MARISSTELLA2
 
Python first day
Python first day
farkhand
 
Migrating from matlab to python
Migrating from matlab to python
ActiveState
 
Intro python
Intro python
kamzilla
 
Python Programming and GIS
Python Programming and GIS
John Reiser
 
Python tutorial
Python tutorial
Shani729
 
Python tutorial
Python tutorial
nazzf
 
COMP41680 - Sample API Assignment¶In [5] .docx
COMP41680 - Sample API Assignment¶In [5] .docx
pickersgillkayne
 
Python_cheatsheet_numpy.pdf
Python_cheatsheet_numpy.pdf
AnonymousUser67
 
Esri International User Conference 2011: Python: Integrating Standard and Thi...
Esri International User Conference 2011: Python: Integrating Standard and Thi...
jasonscheirer
 
Numpy python cheat_sheet
Numpy python cheat_sheet
Zahid Hasan
 
Numpy python cheat_sheet
Numpy python cheat_sheet
Nishant Upadhyay
 
Python.pptx
Python.pptx
SajjadAbdullah4
 
Advanced geoprocessing with Python
Advanced geoprocessing with Python
Chad Cooper
 
Reading and writing spatial data for the non-spatial programmer
Reading and writing spatial data for the non-spatial programmer
Chad Cooper
 
Python_Basics_CheatSheet for Python Engineers
Python_Basics_CheatSheet for Python Engineers
tareqbata1
 
Python Cheat Sheet 2.0.pdf
Python Cheat Sheet 2.0.pdf
Rahul Jain
 
PART 3: THE SCRIPTING COMPOSER AND PYTHON
PART 3: THE SCRIPTING COMPOSER AND PYTHON
Andrea Antonello
 
Python Workshop Part 2. LUG Maniapl
Python Workshop Part 2. LUG Maniapl
Ankur Shrivastava
 
Shrug2017 arcpy data_and_you
Shrug2017 arcpy data_and_you
SHRUG GIS
 
Python first day
Python first day
farkhand
 
Migrating from matlab to python
Migrating from matlab to python
ActiveState
 
Intro python
Intro python
kamzilla
 
Python Programming and GIS
Python Programming and GIS
John Reiser
 
Python tutorial
Python tutorial
Shani729
 
Python tutorial
Python tutorial
nazzf
 
COMP41680 - Sample API Assignment¶In [5] .docx
COMP41680 - Sample API Assignment¶In [5] .docx
pickersgillkayne
 
Python_cheatsheet_numpy.pdf
Python_cheatsheet_numpy.pdf
AnonymousUser67
 
Esri International User Conference 2011: Python: Integrating Standard and Thi...
Esri International User Conference 2011: Python: Integrating Standard and Thi...
jasonscheirer
 
Numpy python cheat_sheet
Numpy python cheat_sheet
Zahid Hasan
 
Ad

Recently uploaded (20)

Techniques for Automatic Device Identification and Network Assignment.pdf
Techniques for Automatic Device Identification and Network Assignment.pdf
Priyanka Aash
 
cnc-processing-centers-centateq-p-110-en.pdf
cnc-processing-centers-centateq-p-110-en.pdf
AmirStern2
 
Cracking the Code - Unveiling Synergies Between Open Source Security and AI.pdf
Cracking the Code - Unveiling Synergies Between Open Source Security and AI.pdf
Priyanka Aash
 
Oh, the Possibilities - Balancing Innovation and Risk with Generative AI.pdf
Oh, the Possibilities - Balancing Innovation and Risk with Generative AI.pdf
Priyanka Aash
 
Raman Bhaumik - Passionate Tech Enthusiast
Raman Bhaumik - Passionate Tech Enthusiast
Raman Bhaumik
 
Curietech AI in action - Accelerate MuleSoft development
Curietech AI in action - Accelerate MuleSoft development
shyamraj55
 
WebdriverIO & JavaScript: The Perfect Duo for Web Automation
WebdriverIO & JavaScript: The Perfect Duo for Web Automation
digitaljignect
 
Connecting Data and Intelligence: The Role of FME in Machine Learning
Connecting Data and Intelligence: The Role of FME in Machine Learning
Safe Software
 
Quantum AI Discoveries: Fractal Patterns Consciousness and Cyclical Universes
Quantum AI Discoveries: Fractal Patterns Consciousness and Cyclical Universes
Saikat Basu
 
Daily Lesson Log MATATAG ICT TEchnology 8
Daily Lesson Log MATATAG ICT TEchnology 8
LOIDAALMAZAN3
 
10 Key Challenges for AI within the EU Data Protection Framework.pdf
10 Key Challenges for AI within the EU Data Protection Framework.pdf
Priyanka Aash
 
Python Conference Singapore - 19 Jun 2025
Python Conference Singapore - 19 Jun 2025
ninefyi
 
Enhance GitHub Copilot using MCP - Enterprise version.pdf
Enhance GitHub Copilot using MCP - Enterprise version.pdf
Nilesh Gule
 
Securing Account Lifecycles in the Age of Deepfakes.pptx
Securing Account Lifecycles in the Age of Deepfakes.pptx
FIDO Alliance
 
" How to survive with 1 billion vectors and not sell a kidney: our low-cost c...
" How to survive with 1 billion vectors and not sell a kidney: our low-cost c...
Fwdays
 
Lessons Learned from Developing Secure AI Workflows.pdf
Lessons Learned from Developing Secure AI Workflows.pdf
Priyanka Aash
 
2025_06_18 - OpenMetadata Community Meeting.pdf
2025_06_18 - OpenMetadata Community Meeting.pdf
OpenMetadata
 
"Database isolation: how we deal with hundreds of direct connections to the d...
"Database isolation: how we deal with hundreds of direct connections to the d...
Fwdays
 
ReSTIR [DI]: Spatiotemporal reservoir resampling for real-time ray tracing ...
ReSTIR [DI]: Spatiotemporal reservoir resampling for real-time ray tracing ...
revolcs10
 
A Constitutional Quagmire - Ethical Minefields of AI, Cyber, and Privacy.pdf
A Constitutional Quagmire - Ethical Minefields of AI, Cyber, and Privacy.pdf
Priyanka Aash
 
Techniques for Automatic Device Identification and Network Assignment.pdf
Techniques for Automatic Device Identification and Network Assignment.pdf
Priyanka Aash
 
cnc-processing-centers-centateq-p-110-en.pdf
cnc-processing-centers-centateq-p-110-en.pdf
AmirStern2
 
Cracking the Code - Unveiling Synergies Between Open Source Security and AI.pdf
Cracking the Code - Unveiling Synergies Between Open Source Security and AI.pdf
Priyanka Aash
 
Oh, the Possibilities - Balancing Innovation and Risk with Generative AI.pdf
Oh, the Possibilities - Balancing Innovation and Risk with Generative AI.pdf
Priyanka Aash
 
Raman Bhaumik - Passionate Tech Enthusiast
Raman Bhaumik - Passionate Tech Enthusiast
Raman Bhaumik
 
Curietech AI in action - Accelerate MuleSoft development
Curietech AI in action - Accelerate MuleSoft development
shyamraj55
 
WebdriverIO & JavaScript: The Perfect Duo for Web Automation
WebdriverIO & JavaScript: The Perfect Duo for Web Automation
digitaljignect
 
Connecting Data and Intelligence: The Role of FME in Machine Learning
Connecting Data and Intelligence: The Role of FME in Machine Learning
Safe Software
 
Quantum AI Discoveries: Fractal Patterns Consciousness and Cyclical Universes
Quantum AI Discoveries: Fractal Patterns Consciousness and Cyclical Universes
Saikat Basu
 
Daily Lesson Log MATATAG ICT TEchnology 8
Daily Lesson Log MATATAG ICT TEchnology 8
LOIDAALMAZAN3
 
10 Key Challenges for AI within the EU Data Protection Framework.pdf
10 Key Challenges for AI within the EU Data Protection Framework.pdf
Priyanka Aash
 
Python Conference Singapore - 19 Jun 2025
Python Conference Singapore - 19 Jun 2025
ninefyi
 
Enhance GitHub Copilot using MCP - Enterprise version.pdf
Enhance GitHub Copilot using MCP - Enterprise version.pdf
Nilesh Gule
 
Securing Account Lifecycles in the Age of Deepfakes.pptx
Securing Account Lifecycles in the Age of Deepfakes.pptx
FIDO Alliance
 
" How to survive with 1 billion vectors and not sell a kidney: our low-cost c...
" How to survive with 1 billion vectors and not sell a kidney: our low-cost c...
Fwdays
 
Lessons Learned from Developing Secure AI Workflows.pdf
Lessons Learned from Developing Secure AI Workflows.pdf
Priyanka Aash
 
2025_06_18 - OpenMetadata Community Meeting.pdf
2025_06_18 - OpenMetadata Community Meeting.pdf
OpenMetadata
 
"Database isolation: how we deal with hundreds of direct connections to the d...
"Database isolation: how we deal with hundreds of direct connections to the d...
Fwdays
 
ReSTIR [DI]: Spatiotemporal reservoir resampling for real-time ray tracing ...
ReSTIR [DI]: Spatiotemporal reservoir resampling for real-time ray tracing ...
revolcs10
 
A Constitutional Quagmire - Ethical Minefields of AI, Cyber, and Privacy.pdf
A Constitutional Quagmire - Ethical Minefields of AI, Cyber, and Privacy.pdf
Priyanka Aash
 

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('[email protected]', 5 '[email protected]', 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 ?