<?xml version="1.0" encoding="UTF-8"?>
<rss version="2.0"
	xmlns:content="http://purl.org/rss/1.0/modules/content/"
	xmlns:wfw="http://wellformedweb.org/CommentAPI/"
	xmlns:dc="http://purl.org/dc/elements/1.1/"
	xmlns:atom="http://www.w3.org/2005/Atom"
	xmlns:sy="http://purl.org/rss/1.0/modules/syndication/"
	xmlns:slash="http://purl.org/rss/1.0/modules/slash/"
	>

<channel>
	<title>Michalis Avraam &#187; Python Points</title>
	<atom:link href="http://michalisavraam.org/category/python-points/feed/" rel="self" type="application/rss+xml" />
	<link>http://michalisavraam.org</link>
	<description>intersecting space and time through gis endeavors</description>
	<lastBuildDate>Wed, 08 Sep 2010 20:03:43 +0000</lastBuildDate>
	<language>en</language>
	<sy:updatePeriod>hourly</sy:updatePeriod>
	<sy:updateFrequency>1</sy:updateFrequency>
	<generator>http://wordpress.org/?v=3.0.3</generator>
		<item>
		<title>The Essential Python Modules for GIS</title>
		<link>http://michalisavraam.org/2010/04/the-essential-python-modules-for-gis/</link>
		<comments>http://michalisavraam.org/2010/04/the-essential-python-modules-for-gis/#comments</comments>
		<pubDate>Wed, 21 Apr 2010 00:41:45 +0000</pubDate>
		<dc:creator>Michalis Avraam</dc:creator>
				<category><![CDATA[GIS* Points]]></category>
		<category><![CDATA[Python Points]]></category>
		<category><![CDATA[gdal]]></category>
		<category><![CDATA[gdal/ogr]]></category>
		<category><![CDATA[geoprocessing]]></category>
		<category><![CDATA[networkx]]></category>
		<category><![CDATA[numpy]]></category>
		<category><![CDATA[ogr]]></category>
		<category><![CDATA[python]]></category>
		<category><![CDATA[python gis]]></category>
		<category><![CDATA[python modules]]></category>
		<category><![CDATA[xlrd]]></category>
		<category><![CDATA[xlwt]]></category>

		<guid isPermaLink="false">http://michalisavraam.org/?p=304</guid>
		<description><![CDATA[With ESRI&#8217;s use of Python as their scripting language and the proliferation of open source GIS, Python became one of the required languages for GIS developers and hobbyists alike. What makes Python powerful is well documented throughout the web, but I want to highlight one very important aspects of Python today: Python Modules. Python Modules <a href='http://michalisavraam.org/2010/04/the-essential-python-modules-for-gis/'>[...]</a>


Related posts:<ol><li><a href='http://michalisavraam.org/2009/06/manipulating-excel-files-using-python-part-1-reading-files/' rel='bookmark' title='Permanent Link: Manipulating Excel files using Python part 1: Reading Excel Files'>Manipulating Excel files using Python part 1: Reading Excel Files</a></li>
</ol>]]></description>
			<content:encoded><![CDATA[<p>With ESRI&#8217;s use of Python as their scripting language and the proliferation of open source GIS, Python became one of the required languages for GIS developers and hobbyists alike. What makes Python powerful is <a href="http://www.stanford.edu/~pgbovine/python-teaching.htm">well documented</a> <a href="http://www.python.org/about/quotes/">throughout</a> <a href="http://www.vni.com/company/whitepapers/html/AnalyticModelinginPython.php">the</a> <a href="http://webhelp.esri.com/arcgisdesktop/9.1/body.cfm?tocVisable=1&amp;ID=1925&amp;TopicName=An%20overview%20of%20writing%20geoprocessing%20scripts">web</a>, but I want to highlight one very important aspects of Python today: Python Modules.</p>
<p>Python Modules are code someone else has written and distributed, in order to make life easier for the rest of us. You may be familiar with the <a href="http://docs.python.org/modindex.html">standard modules that come with Python</a>, like math or datetime, but there are numerous more resources out there for the GIS minded developers. I will be discussing some of the modules I find essential in my work apart from the famous ArcGISScripting module by ESRI: GDAL, numpy, NetworkX, xlrd and xlwt. Let&#8217;s dive in!<span id="more-304"></span></p>
<h3>GDAL &#8211; Geospatial Data Abstraction Layer</h3>
<p>It will come a time in every GIS Professional&#8217;s career when they will need to quickly access information from a random shapefile they have, but do not have access to any GIS software or geoprocessing functionality (think of a laptop on the road, a remote machine not running Windows, etc). GDAL comes to the rescue, providing us such functionalities.</p>
<p>GDAL is a translator library with Python bindings that allows access to raster data using a unified abstract layer. Bundled with it is OGR, which provides similar functionality for vector data. <a href="http://trac.osgeo.org/gdal/wiki/DownloadingGdalBinaries">Download it here</a>.</p>
<p>A quick example of using GDAL:</p>
<pre class="brush: python; title: ;">
import gdal
from gdalconst import *
# Open the raster dataset
dataset = gdal.Open(filename, GA_ReadOnly)
# Print the projection of the data
print dataset.GetProjection()
</pre>
<p>Using OGR:</p>
<pre class="brush: python; title: ;">
import ogr
# Get the driver
driver = ogr.GetDriverByName('ESRI Shapefile')
# Open a shapefile
dataset = driver.Open(shapefileName, 0)
</pre>
<h3>numpy &#8211; Numerical Python</h3>
<p>I cannot think of any GIS practitioner that did not have to manipulate raster data in a peculiar way, only finding that the software at hand doesn&#8217;t allow you to perform many customized functions. If one can interpret raster data (which GDAL above helps us with), then one can use them in Python as a matrix (algebraic matrix). numpy is the best Python package out there for this sort of situation.</p>
<p>numpy is a package that enables n-dimensional array manipulation in Python, as essential part of any scientific endeavor. It also provides linear algebra functionalities, Fourier transforms and random number generators. <a href="http://www.scipy.org/Download">Get it here</a>.</p>
<p>An example of the use of numpy:</p>
<pre class="brush: python; title: ;">
from numpy import *
# Sample IO Table data
ioSample = [[1,2], [3,4]]
# Turn into a numpy array
ioMatrix = array(ioSample)
# Find the inverse of ioMatrix
ioMatrixInv = linalg.inv(ioMatrix)
</pre>
<h3>NetworkX &#8211; Complex Networks Analysis</h3>
<p>While most GIS software out there provides the ability to build networks, sometimes it is easier to build networks quickly and dirty, without having to involve complex GIS software. An analysis of participation by space in an experiment can easily be achieved using the simple, yet powerful NetworkX module.</p>
<p>NetworkX is a Python package for the creation, manipulation, and study of the structure, dynamics, and functions of complex networks. It is hosted by the Los Alamos National Laboratory, and sees active development (presumably sponsored somehow by Los Alamos). <a href="http://networkx.lanl.gov/download.html">Download it here</a>.</p>
<p>A quick sample is shown below:</p>
<pre class="brush: python; title: ;">
import networkx as nx
# Create a graph
g = nx.Graph()
# Populate the graph
g.add_node(1)
g.add_node(2)
g.add_node(3)
# Create edges
g.add_edge(1,2)
g.add_edge(1,3)
# Print the neighbors of node 1 (returns 2)
print g.neighbors(1)
</pre>
<h3>xlrd &#8211; Excel™ File Reader</h3>
<p>All GIS practitioners have been sent &#8220;GIS data&#8221; in an Excel file, either a geocoding result or GPS waypoints, or anything similar. While ideally whoever sent the data would be educated on why it is a bad idea, most often we have to deal with the data without any additional help. xlrd comes into play, allowing you to read the said Excel formatted data into Python with little effort.</p>
<p>xlrd is a Python module that allows one to read Excel files without the need of Microsoft Excel or Windows. It provides access to XLS files for Microsoft Office 2003 or earlier. <a href="http://www.lexicon.net/sjmachin/xlrd.htm">Download it here</a>.</p>
<p>A quick example that will read an XLS file and print it to screen:</p>
<pre class="brush: python; title: ;">
import xlrd
# Open the Excel file
book = xlrd.open_workbook(&quot;excelFile.xls&quot;)
# Read the first sheet in the Excel workbook
sheet = book.sheet_by_index(0)
# Read the first row from column A to E
rowValues = sheet.row_values(0, start_colx=0, end_colx=4)
# Print the row values
for value in rowValues:
    print value
</pre>
<h3>xlwt &#8211; Excel™ file writer</h3>
<p>Business requirements often want results in an Excel file, so some other person, in another department, can run some sort of analysis on the data. Building a distance matrix is fine, but Joe from accounting is using complicated Excel spreadsheets and does not want to bother with database connections or DBF files. This is a situation in which xlwt excels, writing data to an Excel spreadsheet without the need of Excel or manipulation by the mouse.</p>
<p>xlwt is a Python module that, similarly to xlrd mention above, allows for cross platform Excel file creation without the need of Microsoft Office. <a href="https://secure.simplistix.co.uk/svn/xlwt/trunk/">Download it here</a>.</p>
<p>An example follows:</p>
<pre class="brush: python; title: ;">
import xlwt
# Create a new workbook
book = xlwt.Workbook()
# Add a new sheet
sheet = book.add_sheet(&quot;My Sheet&quot;)
# Write the number 5 in the first row, first column
sheet.write(0, 0, 5)
# Save the file
book.save(&quot;myExcelFile.xls&quot;)
</pre>
</pre>
<p>These are my essential Python modules for GIS development. Notice I left quite a few behind, especially those relating to web-based GIS developments. Those will appear in another post in the future. But please, do share your thoughts on what Python modules are essential for your GIS work.</p>
Note: There is a rating embedded within this post, please visit this post to rate it.


<p>Related posts:<ol><li><a href='http://michalisavraam.org/2009/06/manipulating-excel-files-using-python-part-1-reading-files/' rel='bookmark' title='Permanent Link: Manipulating Excel files using Python part 1: Reading Excel Files'>Manipulating Excel files using Python part 1: Reading Excel Files</a></li>
</ol></p>]]></content:encoded>
			<wfw:commentRss>http://michalisavraam.org/2010/04/the-essential-python-modules-for-gis/feed/</wfw:commentRss>
		<slash:comments>13</slash:comments>
		</item>
		<item>
		<title>Loading the Geoprocessor Safely</title>
		<link>http://michalisavraam.org/2010/02/loading-the-geoprocessor-safely/</link>
		<comments>http://michalisavraam.org/2010/02/loading-the-geoprocessor-safely/#comments</comments>
		<pubDate>Thu, 25 Feb 2010 20:52:25 +0000</pubDate>
		<dc:creator>Michalis Avraam</dc:creator>
				<category><![CDATA[Python Geoprocessing]]></category>
		<category><![CDATA[Python Points]]></category>
		<category><![CDATA[arcgisscripting]]></category>
		<category><![CDATA[geoprocessing]]></category>
		<category><![CDATA[python]]></category>

		<guid isPermaLink="false">http://michalisavraam.org/?p=275</guid>
		<description><![CDATA[Often times people write geoprocessing scripts that others try to incorporate in their work. This is done through modules or packages in Python. This is wonderful when one wishes to share their work, but it can also be bothersome if the module you are loading assumes that there is no geoprocessor loaded. This little script <a href='http://michalisavraam.org/2010/02/loading-the-geoprocessor-safely/'>[...]</a>


Related posts:<ol><li><a href='http://michalisavraam.org/2009/10/understanding-the-geoprocessor-programming-model-part/' rel='bookmark' title='Permanent Link: Understanding the Geoprocessor Programming Model part 1'>Understanding the Geoprocessor Programming Model part 1</a></li>
</ol>]]></description>
			<content:encoded><![CDATA[<p>Often times people write geoprocessing scripts that others try to incorporate in their work. This is done through modules or packages in Python. This is wonderful when one wishes to share their work, but it can also be bothersome if the module you are loading assumes that there is no geoprocessor loaded. This little script will help you safely load the geoprocessor object, either from an instantiation by the main program, or from scratch.</p>
<p><span id="more-275"></span>The method I use to load the geoprocessor, while verbose, ensures that if anyone loads the geoprocessor before they use any of my module functions, any of their settings remain intact. This is achieved as follows:</p>
<ol>
<li>Check if the <em>arcgisscripting</em> module was loaded.
<ol>
<li>If it was not loaded, obviously the geoprocessor is not instantiated. Import, instantiate and return.</li>
</ol>
</li>
<li>If the <em>arcgisscripting</em> module was loaded, check the variables the user created in the main program.
<ol>
<li>If a variable is found to be of type &#8216;<em>geoprocessor object</em>&#8216;, then return that object.</li>
</ol>
</li>
<li>If no variable is found of type &#8216;<em>geoprocessor object</em>&#8216;, create it and return it.</li>
</ol>
<p>The code can be found below. Please review and use as you wish. If you have any comments or questions about it, please leave a comment.</p>
<pre class="brush: python; title: ;">
&quot;&quot;&quot;
Loads the geoprocessor safely, ensuring that it is not loaded
twice (to avoid overwriting parameters).

Usage: load()

Returns: a geoprocessor object.

Note: Geoprocessor Version returned is 9.3

&quot;&quot;&quot;
import sys

def load(version=None):
    # Check if the arcgisscripting module was loaded
    if &quot;arcgisscripting&quot; not in sys.modules:
        # The arcgisscripting module was never loaded Try to load it.
        print &quot;arcgisscripting not loaded&quot;
        print &quot;Trying to load arcgisscripting&quot;
        try:
            import arcgisscripting
        except ImportError, errorDetail:
            sys.exit(&quot;Error loading arcgisscriping. Is ArcGIS installed?\n&quot; + errorDetail)
        # Try to create a geoprocessor instantiation
        print &quot;Trying to create the geoprocessor instance&quot;
        try:
            gp = arcgisscripting.create(9.3)
        except:
            sys.exit(&quot;Error creating geoprocessor object. Exiting\n&quot; + str(sys.exc_info()))
        # Return the geoprocessor instance
        print &quot;Done!&quot;
        return gp
    else:
        # arcgisscripting was loaded. Is the geoprocessor instantiated?
        print &quot;arcgisscripting was already loaded. Searching for geoprocessor...&quot;
        # Get the global variables
        globalVars = vars(sys.modules[&quot;__main__&quot;])
        for item, value in globalVars.iteritems():
            # Loop through global variables, ignore internals
            if not item.startswith(&quot;__&quot;):
                # Check the type of the variable
                if type(globalVars[item]).__name__ == 'geoprocessing object':
                    # If the variable is the geoprocessor, return it
                    print &quot;Found geoprocessor instance as&quot;, item
                    return globalVars[item]
        # If we are here, the module is loaded but no gp instantiated
        # Try to create a geoprocessor instantiation
        try:
            print &quot;arcgisscripting loaded but not instantiated. Instantiating now...&quot;
            gp = sys.modules[&quot;arcgisscripting&quot;].create(9.3)
        except:
            sys.exit(&quot;Error creating geoprocessor object. Exiting\n&quot; + str(sys.exc_info()))
        # Return the geoprocessor instance
        return gp
 </pre>
Note: There is a rating embedded within this post, please visit this post to rate it.


<p>Related posts:<ol><li><a href='http://michalisavraam.org/2009/10/understanding-the-geoprocessor-programming-model-part/' rel='bookmark' title='Permanent Link: Understanding the Geoprocessor Programming Model part 1'>Understanding the Geoprocessor Programming Model part 1</a></li>
</ol></p>]]></content:encoded>
			<wfw:commentRss>http://michalisavraam.org/2010/02/loading-the-geoprocessor-safely/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>Understanding the Geoprocessor Programming Model part 3</title>
		<link>http://michalisavraam.org/2010/02/understanding-the-geoprocessor-programming-model-part-3/</link>
		<comments>http://michalisavraam.org/2010/02/understanding-the-geoprocessor-programming-model-part-3/#comments</comments>
		<pubDate>Thu, 04 Feb 2010 01:47:02 +0000</pubDate>
		<dc:creator>Michalis Avraam</dc:creator>
				<category><![CDATA[GIS* Points]]></category>
		<category><![CDATA[Python Geoprocessing]]></category>
		<category><![CDATA[Python Points]]></category>
		<category><![CDATA[arcgisscripting]]></category>
		<category><![CDATA[describe]]></category>
		<category><![CDATA[ESRI]]></category>
		<category><![CDATA[geoprocessing]]></category>
		<category><![CDATA[python]]></category>

		<guid isPermaLink="false">http://michalisavraam.org/?p=229</guid>
		<description><![CDATA[After a long delay, it is time for the third installment of understanding the Geoprocessor Programming Model that will deal with the Describe object. If you missed the last two parts, feel free to look at them first (Part 1: understanding what the geoprocessor is, and Part 2: accessing data with the geoprocessor). As always, <a href='http://michalisavraam.org/2010/02/understanding-the-geoprocessor-programming-model-part-3/'>[...]</a>


Related posts:<ol><li><a href='http://michalisavraam.org/2009/02/accessing-geometries-using-the-geoprocessor-updated/' rel='bookmark' title='Permanent Link: Accessing Geometries using the Geoprocessor (Updated)'>Accessing Geometries using the Geoprocessor (Updated)</a></li>
</ol>]]></description>
			<content:encoded><![CDATA[<p>After a long delay, it is time for the third installment of understanding the Geoprocessor Programming Model that will deal with the Describe object. If you missed the last two parts, feel free to look at them first (<a href="http://michalisavraam.org/2009/10/understanding-the-geoprocessor-programming-model-part/">Part 1: understanding what the geoprocessor is</a>, and <a href="http://michalisavraam.org/2009/10/understanding-the-geoprocessor-programming-model-part-2/">Part 2: accessing data with the geoprocessor</a>). As always, comments are welcomed and encouraged.<span id="more-229"></span></p>
<div id="attachment_234" class="wp-caption alignright" style="width: 510px"><a href="http://michalisavraam.org/wp-content/uploads/2009/11/describe.png"><img class="size-full wp-image-234" title="The Describe Object" src="http://michalisavraam.org/wp-content/uploads/2009/11/describe.png" alt="The Describe Object" width="500" height="540" /></a><p class="wp-caption-text">The Describe Realm</p></div>
<p>As mentioned earlier, the geoprocessor gives us the ability to access or create data to perform various operations. These operation vary in type and content, but more often than not are performed on data we are not intimately familiar with. This can become a problem quite quickly, as we need to know the names of fields in the datasets, as well as other characteristics (the type of data we are dealing with, spatial references, geographical extent and other). The solution to this lack of knowledge comes through the <em>describe</em> object which provides users with methods to identify all unknown information beforehand. In the most basic form of usage, one uses the <em>describe</em> object on a dataset, accessing the bottom left box in the diagram, the <em>Describe Object Properties</em>. The Python code to achieve this follows:</p>
<pre class="brush: python; title: ;">
import arcgisscripting
# Import the module provided by ESRI

gp = arcgisscripting.create(9.3)
# Create the geoprocessor object

dataset = r&quot;c:\data\testData.shp&quot;
# The location of the data. This is usually
#   not hardcoded but discovered with List methods

dsc = gp.Describe(dataset)
# Create a describe object for the dataset

print dsc.DataType
# Print the data type of our dataset

print dsc.CatalogPath
# Print the path to the dataset
</pre>
<p>With the above simple example, we managed to read the Data Type and Catalog Path of a dataset. While this seems simple, it can become a very powerful tool, when on considers the possible return values (listed below).</p>
<table border="1" cellspacing="0" cellpadding="2" align="center">
<tbody>
<tr style="background-color: #dcdcdc;">
<td align="left"><strong>Return Value</strong></td>
<td align="left"><strong>Data Type</strong></td>
</tr>
<tr>
<td align="left">FeatureDataset</td>
<td align="left">Containers for data that include spatial reference and extent of contents.</td>
</tr>
<tr>
<td align="left">FeatureClass</td>
<td align="left">Feature class in a geodatabase, a shapefile if standalone.</td>
</tr>
<tr>
<td align="left">Table</td>
<td align="left">A geodatabase or standalone table.</td>
</tr>
<tr>
<td align="left">RelationshipClass</td>
<td align="left">A geodatabase class storing relationships.</td>
</tr>
<tr>
<td align="left">RasterDataset</td>
<td align="left">A raster dataset type.</td>
</tr>
<tr>
<td align="left">RasterBand</td>
<td align="left">A raster band.</td>
</tr>
<tr>
<td align="left">RasterCatalog</td>
<td align="left">A raster catalog.</td>
</tr>
<tr>
<td align="left">Workspace</td>
<td align="left">A workspace as defined by ESRI (directory or database).</td>
</tr>
</tbody>
</table>
<p>As you can see, the return values as listed above correspond to different objects in our diagram (the boxes in the first image above). This means that it would be trivial for us to move between the first access we have into the <em>Describe</em> realm (through the Describe object) and move to any other box of our choice when we are not familiar with what possible data we have.</p>
<h2>Retrieving Information about data: Feature Classes</h2>
<div id="attachment_236" class="wp-caption alignleft" style="width: 210px"><a href="http://michalisavraam.org/wp-content/uploads/2009/11/featureClass.png"><img class="size-full wp-image-236" title="FeatureClass Object Properties" src="http://michalisavraam.org/wp-content/uploads/2009/11/featureClass.png" alt="FeatureClass Object Properties" width="200" height="209" /></a><p class="wp-caption-text">FeatureClass Object Properties</p></div>
<p>The most commonly used types of data in GIS now seems to be feature classes, either standalone (in the form of shapefiles) or in a geodatabase. As such, we will use the example of a feature class to retrieve information about out data. This is of course not the only type of data one can use, so please refer to the image on the top for more information.</p>
<p>As you can see from the diagram on the left, feature classes have specific information associated with them, including what feature type they are of, their shape type, and the shape field name we used in part two of this series. We will dive right into it by trying to identify what shape type our feature class has, and what type of feature it is.</p>
<pre class="brush: python; title: ;">
import arcgisscripting
# Import the module provided by ESRI

gp = arcgisscripting.create(9.3)
# Create the geoprocessor object

dataset = r&quot;c:\data\testData.shp&quot;
# The location of the data. This is usually
#   not hardcoded but discovered with List methods

dsc = gp.Describe(dataset)
# Create a describe object for the dataset
# As we know the dataset is of type FeatureClass,
#   all the properties of the FeatureClass object
#   are available to us now.

print dsc.ShapeType
# Print what type of shape we have
#   (point, polygon, polyline, etc)

print dsc.FeatureType
# Print what type of features are stored
#   (simple, annotation, dimension, etc)
</pre>
<p>With the above code we can identify what type of shape we have and the type of feature stored. For possible values to these properties, please <a href="http://webhelp.esri.com/arcgisdesktop/9.3/index.cfm?TopicName=FeatureClass_properties">check this help file</a>.</p>
<div id="attachment_237" class="wp-caption alignright" style="width: 210px"><a href="http://michalisavraam.org/wp-content/uploads/2009/11/table.png"><img class="size-full wp-image-237" title="Table Properties" src="http://michalisavraam.org/wp-content/uploads/2009/11/table.png" alt="Table Properties" width="200" height="108" /></a><p class="wp-caption-text">Table Properties</p></div>
<p>In the FeatureClass Properties object image above, on the bottom, you can see that there are also <em>Table Properties</em> and<em> Dataset Properties</em> listed. This means that when you have a feature class, you automatically gain access to those properties as well (as a feature class has them embedded). Therefore, we can use this to our advantage to further retrieve information about our feature class, like the name of all fields within the feature class. The example below shows you how to achieve this.</p>
<pre class="brush: python; title: ;">
import arcgisscripting
# Import the module provided by ESRI

gp = arcgisscripting.create(9.3)
# Create the geoprocessor object

data = r&quot;c:\data\testData.shp&quot;
# The location of the data. This is usually
#   not hardcoded but discovered with List methods

dsc = gp.Describe(data)
# Create a describe object for the data
# As we know the dataset is of type FeatureClass,
#   all the properties of the FeatureClass object
#   and inherited objects are available to us now.

dataFlds = dsc.Fields
# Retrieve a list of fields in the table of the
#   feature class as a Python list. Note the fields
#   are of Field Object type.

for fld in dataFields:
    print fld.Name
</pre>
<div id="attachment_235" class="wp-caption alignright" style="width: 210px"><a href="http://michalisavraam.org/wp-content/uploads/2009/11/dataset.png"><img class="size-full wp-image-235" title="Dataset Properties" src="http://michalisavraam.org/wp-content/uploads/2009/11/dataset.png" alt="Dataset Properties" width="200" height="118" /></a><p class="wp-caption-text">Dataset Properties</p></div>
<p>What he have done on the above example is run the ListFields() method mentioned in an older article (<a href="http://michalisavraam.org/2009/08/using-the-geoprocessors-list-methods/">Using the Geoprocessor&#8217;s List Methods</a>). Similarly, one can follow the Dataset Properties object (shown on your right) to access information like the extent of the data, or the spatial reference system. Don&#8217;t forget, both of those return an object, which has a corresponding box in the geoprocessor programming model diagram, so you need to treat them as such.</p>
<p>In this installment, I have shown you how one can use the <em>Describe</em> object the geoprocessor makes available to us to retrieve information about our data. While I did not provide complete examples of every single possible option available, hopefully by reading this post you are able to navigate your options better to achieve your goals.</p>
<p>As always, comments are encouraged and I am willing to answer any questions you may have.</p>
Note: There is a rating embedded within this post, please visit this post to rate it.


<p>Related posts:<ol><li><a href='http://michalisavraam.org/2009/02/accessing-geometries-using-the-geoprocessor-updated/' rel='bookmark' title='Permanent Link: Accessing Geometries using the Geoprocessor (Updated)'>Accessing Geometries using the Geoprocessor (Updated)</a></li>
</ol></p>]]></content:encoded>
			<wfw:commentRss>http://michalisavraam.org/2010/02/understanding-the-geoprocessor-programming-model-part-3/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>Understanding the Geoprocessor Programming Model part 2</title>
		<link>http://michalisavraam.org/2009/10/understanding-the-geoprocessor-programming-model-part-2/</link>
		<comments>http://michalisavraam.org/2009/10/understanding-the-geoprocessor-programming-model-part-2/#comments</comments>
		<pubDate>Mon, 19 Oct 2009 17:00:04 +0000</pubDate>
		<dc:creator>Michalis Avraam</dc:creator>
				<category><![CDATA[GIS* Points]]></category>
		<category><![CDATA[Python Geoprocessing]]></category>
		<category><![CDATA[Python Points]]></category>
		<category><![CDATA[arcgisscripting]]></category>
		<category><![CDATA[ESRI]]></category>
		<category><![CDATA[geoprocessing]]></category>
		<category><![CDATA[python]]></category>

		<guid isPermaLink="false">http://michalisavraam.org/?p=198</guid>
		<description><![CDATA[In the first part of this series I covered access to the geoprocessor and how one can navigate the first part of the diagram of the model. If you are not familiar with the geoprocessor, please have a quick look at that post to understand the geoprocessing model ESRI provides. In this post I will <a href='http://michalisavraam.org/2009/10/understanding-the-geoprocessor-programming-model-part-2/'>[...]</a>


Related posts:<ol><li><a href='http://michalisavraam.org/2009/02/accessing-geometries-using-the-geoprocessor-updated/' rel='bookmark' title='Permanent Link: Accessing Geometries using the Geoprocessor (Updated)'>Accessing Geometries using the Geoprocessor (Updated)</a></li>
</ol>]]></description>
			<content:encoded><![CDATA[<p>In the <a href="http://michalisavraam.org/2009/10/understanding-the-geoprocessor-programming-model-part/">first part of this series</a> I covered access to the geoprocessor and how one can navigate the first part of the diagram of the model. If you are not familiar with the geoprocessor, please have a quick look at that post to understand the geoprocessing model ESRI provides.</p>
<p>In this post I will finish covering the bottom left part of the model that deals with direct access to features and their geometry. In order to do that, we will discuss cursors, features and geometries.</p>
<h3><span id="more-198"></span>Spatial Data Primer</h3>
<p>Before we begin discussing deep access to data, we need to define what spatial data are. In essence, there are two types of spatial data, vector and raster data. An easy way to understand the difference is to imagine raster data as images, while vector data are defined by points, lines and polygons. What is special about spatial data is their dimension of space, or location. Raster data offer extensive coverage of an area, in which our spatial data offer a regular grid of cells that provide data. Space in this case is depended on the location of the cell in the raster file (and therefore implicit location). Vector files on the other hand contain explicit information about the location of things (providing coordinates). Data are then associated with the locations of features. We will be dealing with vector data mostly, so a further investigation is warranted.</p>
<p>In order to represent the world in spatial data, we choose a type of vector data we want to use (for example, choosing points to represent trees, lines to represent road networks, etc). Each of the features in the world get assigned two types of data: spatial characteristics (for a point, an x,y pairs, for a line, a series of points, etc.) and non-spatial characteristics (think of them as attributes). A file that contains all the trees in a neighborhood then includes a list of all the trees, with each tree having a location attribute, and a set of attributes that describe the tree (like type of tree, or age of tree, etc). Therefore, spatial data are defined as follows:</p>
<ul>
<li>A file dealing with a specific type of feature in the world.
<ul>
<li>The file has a list of features that all satisfy the requirement of belonging in that type of feature.
<ul>
<li>Each feature contains a spatial footprint for where it is located.</li>
<li>Along with location, each feature contains zero or more characteristics that are aspatial but refer to the feature itself.</li>
</ul>
</li>
</ul>
</li>
</ul>
<p>Similarly, when one tries to access the geometry or the characteristics of a specific feature in our data, one has to first access the file we need, within the file, identify the right feature we need, and then eventually, within the feature find the geometry and/or the characteristics associated with it.</p>
<h3>Accessing Data Using the Geoprocessor</h3>
<div id="attachment_199" class="wp-caption aligncenter" style="width: 810px"><img class="size-full wp-image-199" title="From the Geoprocessor to Geometry" src="http://michalisavraam.org/wp-content/uploads/2009/10/gpToGeometry.png" alt="From the Geoprocessor to Geometry" width="800" height="180" /><p class="wp-caption-text">From the Geoprocessor to Geometry</p></div>
<p>The image above shows the path one needs to travel within the Geoprocessor to access a Geometry. The cyan box on the left represents the commands available to the geoprocessor object, as discusses in the previous post. The commands that include the word Cursor have an arrow to their right, that show they can access rows, which is actually a representation of the spatial data file in Python. From there on, one can access a single row (the third box from the left), which can eventually lead to the <em>Geometry</em> object on the left. So in the geoprocessing world, in order to access a geometry (or spatial characterics of a feature), we need to do the following:</p>
<ol>
<li>Create the geoprocessor object.</li>
<li>Call the appropriate cursor command to receive a <em>rows</em> object, which is a Python representation of the file we need to access.</li>
<li>Within the <em>rows</em> object, we call the <em>Next()</em> or <em>NewRow()</em> command to receive an individual feature, represented as a single <em>row</em>.</li>
<li>The <em>row</em> object allows us to directly access characteristics of the file, including the <em>Geometry</em> object. Please note that the characteristics are actually variables now, and not methods.</li>
</ol>
<p>A question people often ask is how one knows which path to follow when they need to access a specific object (or box in the diagram). If you are not intimately familiar with the model, there is one method to follow: Identify the object you want, and then follow the arrows in reverse to find the methods that can get you there. Once you have those steps reverse them and you have a workflow. Remember, you will always need to end up in the cyan, geoprocessor object, as this is your only starting point.</p>
<h4>From the Geoprocessor to Spatial File Access</h4>
<p>There are three methods to access your spatial file, as shown in the diagram, explained below:</p>
<ul>
<li><strong>InsertCursor</strong>: The insert cursor allows you to access a spatial file with the sole purpose of adding new features (or rows). Use this cursor to add more features to a file.</li>
<li><strong>SearchCursor</strong>: The search cursor allows you to access a spatial file with the sole purpose of reading features (rows). Use this cursor to read the characteristics of each feature.</li>
<li><strong>UpdateCursor</strong>: The update cursor allows you to access a spatial file in order to update values in each feature (row), or completely remove it. Use this cursor to update characteristics (including geometry) of a feature, or to remove the feature itself.</li>
</ul>
<p>The required parameter for each of these cursor is the file you want to access, called InputValue in the diagram. Here is an example of how to use each cursor:</p>
<pre class="brush: python; title: ;">
import arcgisscripting
# Import the module provided by ESRI

gp = arcgisscripting.create(9.3)
# Create the geoprocessor object

fcWrite = gp.InsertCursor(r&quot;c:\data\testWrite.shp&quot;)
# Create an insert cursor that points to the testWrite.shp file.
# The returned value fcWrite is actually a rows object.
# You are now able to add new features to the file.

fcRead = gp.SearchCursor(r&quot;c:\data\testRead.shp&quot;)
# Create a search cursor that points to the testRead.shp file.
# The returned value fcRead is actually a rows object.
# You are now able to read the information about features from the file.

fcUpdate = gp.UpdateCursor(r&quot;c:\data\testUpdate.shp&quot;)
# Create an update cursor that points to the testUpadate.shp file.
# The returned value fcUpdate is actually a rows object.
# You are now able to update values in features, of completely remove them from the file.
</pre>
<p>If you follow the above examples, you manage to escape from the geoprocessor object (the cyan box) and move to the <em>rows</em> object, the first yellow box on the left. Note that the <em>rows</em> object has different methods available depending on how you access it.</p>
<h4>From the Rows Object to a Single Row</h4>
<div id="attachment_200" class="wp-caption aligncenter" style="width: 610px"><img class="size-full wp-image-200 " title="From the Rows Object to the Row Object" src="http://michalisavraam.org/wp-content/uploads/2009/10/rowsToRow.png" alt="From the file to a single row" width="600" height="305" /><p class="wp-caption-text">From the file to a single row</p></div>
<p>Now that you have access to the <em>rows</em> object, you can continue accessing the file by individual feature (or row). Depending on the Cursor method you used, you will have the following options available to you:</p>
<ul>
<li><strong>SearchCursor <em>Rows</em> Object</strong>: This provides you with read-only access to the elements/features of your file. As such, there are two methods available: Next() and Reset(). As you may infer from their name, Next() will provide to you the next feature as a <em>row</em> object, while the Reset() method simply returns the pointed to the specific row in the beginning of the file.</li>
<li><strong>InsertCursor <em>Rows</em> Object</strong>: As the InsertCursor() method provides the ability to add new features in the file, the methods available are NewRow(), InsertRow() and Reset(). This creates some confusion, but it is easy to distinguish what happens when you understand the internals. NewRow() creates a new and empty <em>row</em> object in memory, which allows you to create your new feature. This <em>row</em> object remains in memory until one calls the InsertRow() function, which will save the <em>row</em> object to your file. The Reset() method functions as with the SearchCursor <em>Rows</em> object explained above.</li>
<li><strong>UpdateCursor <em>Rows</em> Object</strong>: As the UpdateCursor() provides you the most functionality, it comes with more methods: Next(), Reset(), UpdateRow() and DeleteRow(). The Next() and Reset() methods function the same way as with the SearchCursor <em>Rows</em> object. UpdateRow() is similar to the InsertRow() method of the InsertCursor <em>Rows</em> object. Given a <em>row</em> object, it will update the feature the cursor is set on. Similarly, the DeleteRow() method will delete the current <em>row</em> object the cursor points to.</li>
</ul>
<p>Examples on how to use the commands follow:</p>
<p>Example 1: Writing a new feature</p>
<pre class="brush: python; title: ;">
# Example 1: Create a new Row
import arcgisscripting
# Import the module provided by ESRI

gp = arcgisscripting.create(9.3)
# Create the geoprocessor object

fcWrite = gp.InsertCursor(r&quot;c:\data\testWrite.shp&quot;)
# Create an insert cursor that points to the testWrite.shp file.
# The returned value fcWrite is actually a rows object.

fcWrite.Reset()
# Reset the cursor to the rows object

fcRow = fcWrite.NewRow()
# Create a new row object in memory, saved in the fcRow variable

# Manipulate the row here.

fcWrite.InsertRow(fcRow)
# Save the row object back to our file
</pre>
<p>Example 2: Reading a feature</p>
<pre class="brush: python; title: ;">
 # Example 2: Read the n feature of a file
 import arcgisscripting
 # Import the module provided by ESRI

 gp = arcgisscripting.create(9.3)
 # Create the geoprocessor object

 fcRead = gp.InsertCursor(r&quot;c:\data\testRead.shp&quot;)
 # Create an insert cursor that points to the testRead.shp file.
 # The returned value fcRead is actually a rows object.

 fcRead.Reset()
 # Reset the cursor to the rows object

 fcRow = fcRead.Next()
 # Read the first row of the file and save it to the fcRow variable

 # Read the information for the feature here

# If you need to find a specific feature, you need to continue your search
# Use a while loop to achieve this
while fcRow:
    # Test whether this feature is the one you want
    # When you found the feature, you can use break to end the loop
    # If the feature is not the right one, keep trying
    fcRow = fcRead.Next()
 </pre>
<p>Example 3: Updating and Deleting Rows</p>
<pre class="brush: python; title: ;">
# Example 3: Updating and Deleting Rows
import arcgisscripting
# Import the module provided by ESRI

gp = arcgisscripting.create(9.3)
# Create the geoprocessor object

fcUpdate = gp.UpdateCursor(r&quot;c:\data\testUpdate.shp&quot;)
# Create an update cursor that points to the testUpadate.shp file.
# The returned value fcUpdate is actually a rows object.

fcUpdate.Reset()
# Reset the cursor to the rows object

fcRow = fcUpdate.Next()
# Receive the first row

# Loop through the rows until you find one to delete and one to update
while fcRow:
    # If this is the row that needs deleting, then
        fcUpdate.DeleteRow(fcRow)
        # Call the DeleteRow() method with the current row as a parameter
    # If this is the row that needs updating, then
        # Perform the update to the row
        fcUpdate.UpdateRow(fcRow)
        # Call the UpdateRow() method with the current row as a parameter
</pre>
<h4>Manipulating Individual Features and Geometries</h4>
<p>If you followed the above examples, then you are aware on how one can access an individual feature from a file. The question then remains on how one manipulates that row. Below are some explanations on how one can perform this.</p>
<div id="attachment_201" class="wp-caption aligncenter" style="width: 610px"><img class="size-full wp-image-201" title="Rows and Geometries " src="http://michalisavraam.org/wp-content/uploads/2009/10/rowToGeometry.png" alt="Individual Features (row) and their Geometry" width="600" height="227" /><p class="wp-caption-text">Individual Features (row) and their Geometry</p></div>
<p>As with the <em>Rows</em> object, there are different versions of the <em>Row</em> object depending on who calls it. The two possibilities are:</p>
<ul>
<li><strong><em>Row</em> object derived from a SearchCursor</strong>: This object provides the GetValue() method that allows one to read values associated with a field. Along with the method, there is a collection of read-only variables that represent the fields/attributes the row represents.</li>
<li><strong><em>Row</em> object derived from an InsertCursor or UpdateCursor</strong>: This object provides what the read-only version provides, with the variables representing fields/attributes being write-enabled as well. The SetValue() method is also provided to allow one to set new values to fields.</li>
</ul>
<div id="attachment_202" class="wp-caption alignright" style="width: 310px"><img class="size-full wp-image-202" title="fieldObject" src="http://michalisavraam.org/wp-content/uploads/2009/10/fieldObject.png" alt="The Field Object" width="300" height="224" /><p class="wp-caption-text">The Field Object</p></div>
<p>Before we continue on with the idea of geometries, we need to show how one can access the field names. Often we know the names of fields/attributes because we are familiar with the dataset or have access to the metadata. Another way to get familiar with the names of the fields though exists, and is through the ListFields() method available to the geoprocessor object. This command will return a Python list that includes all the attributes available to you, as <em>Field</em> objects. What this object provides to you is a set of variables that are read-only and make available to you information like the name, alias, domain, editable ability and more information about the field. Please have a look at the diagram on the right for a full listing of information included in a <em>Field</em> object.</p>
<pre class="brush: python; title: ;">
# Example of finding out the fields available in a file
import arcgisscripting
# Import the module provided by ESRI

gp = arcgisscripting.create(9.3)
# Create the geoprocessor object

fieldsList = gp.ListFields(r&quot;c:\data\test.shp&quot;)
# Call the ListFields() method on the test.shp file
# The returned list is saved in fieldsList

for field in fieldsList:
# Loop through all the field
    print field.Name
# Print the name of the field
</pre>
<p>This is one way to also identify the field that includes the geometry. Unfortunately, depending on the type of file you have (or database for that matter), the name may change. There is a trick to find the actual name of the field that stores geometry, but it will be covered in another part. For now, here is how one can do it:</p>
<pre class="brush: python; title: ;">
# Example of finding out the fields available in a file
import arcgisscripting
# Import the module provided by ESRI

gp = arcgisscripting.create(9.3)
# Create the geoprocessor object

fcDsc = gp.Describe(r&quot;c:\data\test.shp&quot;)
# Get the descriptor of the file
geometryField = fcDsc.ShapeFieldName
# Get the geometry(shape) field name from the description
</pre>
<p>As you now know what the name of the geometry field is, you can access is as mentioned before with the GetValue() method. Similarly, you can save a geometry using the SetValue() method. It is important to remember that geometries in the ESRI world are <em>Geometry</em> objects of multiple parts which are held in <em>Array</em> objects holding one or more <em>Point</em> objects. This means when you use the GetValue() method, you first receive a <em>Geometry</em> object. Within that object, you will call the GetPart() method to receive an <em>Array</em> object, which in turn holds a number of <em>Point</em> objects, which are called through the Next() method. An example follows to help you understand this.</p>
<pre class="brush: python; title: ;">
# Example of accessing a Geometry of a feature / print geometry type
import arcgisscripting
# Import the module provided by ESRI

gp = arcgisscripting.create(9.3)
# Create the geoprocessor object

fcDsc = gp.Describe(r&quot;c:\data\test.shp&quot;)
# Get the descriptor of the file
geometryField = fcDsc.ShapeFieldName
# Get the geometry(shape) field name from the description

srcCursor = gp.SearchCursor(r&quot;c:\data\test.shp&quot;)
# Create a search cursor to the file

row = srcCursor.Next()
# Grab the first row

while row:
# Loop through the features/rows
rowGeom = row.Getvalue(geometryField)
# Grab the geometry of the row

print rowGeom.Type
# Print the type of the geometry

row = srcCursor.Next()
# Grab the next row
</pre>
<p>With this installment, you should have the knowledge to navigate the Geoprocessor Programming Model on the bottom, where accessor methods for files reside. Also, you should be able to access a Geometry object for every vector dataset you have available. In the next installment we will further navigate the programming model.</p>
<p>Note: Thanks to Eric for catching a Python error.</p>
Note: There is a rating embedded within this post, please visit this post to rate it.


<p>Related posts:<ol><li><a href='http://michalisavraam.org/2009/02/accessing-geometries-using-the-geoprocessor-updated/' rel='bookmark' title='Permanent Link: Accessing Geometries using the Geoprocessor (Updated)'>Accessing Geometries using the Geoprocessor (Updated)</a></li>
</ol></p>]]></content:encoded>
			<wfw:commentRss>http://michalisavraam.org/2009/10/understanding-the-geoprocessor-programming-model-part-2/feed/</wfw:commentRss>
		<slash:comments>2</slash:comments>
		</item>
		<item>
		<title>Understanding the Geoprocessor Programming Model part 1</title>
		<link>http://michalisavraam.org/2009/10/understanding-the-geoprocessor-programming-model-part/</link>
		<comments>http://michalisavraam.org/2009/10/understanding-the-geoprocessor-programming-model-part/#comments</comments>
		<pubDate>Fri, 16 Oct 2009 18:21:31 +0000</pubDate>
		<dc:creator>Michalis Avraam</dc:creator>
				<category><![CDATA[GIS* Points]]></category>
		<category><![CDATA[Python Geoprocessing]]></category>
		<category><![CDATA[Python Points]]></category>
		<category><![CDATA[arcgisscripting]]></category>
		<category><![CDATA[ESRI]]></category>
		<category><![CDATA[geoprocessing]]></category>
		<category><![CDATA[python]]></category>

		<guid isPermaLink="false">http://michalisavraam.org/?p=183</guid>
		<description><![CDATA[A question often asked when people venture into the wonderful world of Python Geoprocessing with ESRI is how one can read the programming model they make available on their website. As it may not be easily interpreted when one begins programming, I will do my best to unpack it and explain how one can use <a href='http://michalisavraam.org/2009/10/understanding-the-geoprocessor-programming-model-part/'>[...]</a>


Related posts:<ol><li><a href='http://michalisavraam.org/2010/02/loading-the-geoprocessor-safely/' rel='bookmark' title='Permanent Link: Loading the Geoprocessor Safely'>Loading the Geoprocessor Safely</a></li>
</ol>]]></description>
			<content:encoded><![CDATA[<p><a href="http://webhelp.esri.com/arcgisdesktop/9.3/pdf/Geoprocessor_93.pdf"><img class="size-full wp-image-185 alignright" title="ESRI's Geoprocessing Programming Model" src="http://michalisavraam.org/wp-content/uploads/2009/10/esriGeoprocessingProgrammingModel1.png" alt="ESRI's Geoprocessing Prorgamming Model" width="150" height="67" /></a></p>
<p>A question often asked when people venture into the wonderful world of Python Geoprocessing with <a href="http://www.esri.com/">ESRI</a> is how one can read the <a href="http://webhelp.esri.com/arcgisdesktop/9.3/pdf/Geoprocessor_93.pdf">programming model</a> they make available on their website. As it may not be easily interpreted when one begins programming, I will do my best to unpack it and explain how one can use it more effectively. All images presented here are extracts from the actual model presented by ESRI on their website.</p>
<p><span id="more-183"></span></p>
<h3>Dual Usages for the Geoprocessor</h3>
<p>The geoprocessor within Python can be used for two different purposes: to access tools provided by ESRI to manipulate data (the tools one sees in the ArcToolbox), and to programatically manipulate data using the underlying structures provided by ESRI. To further explain this process, a little understanding of how software works is needed. A software package usually involves multiple components. At the heart of software are basic operations and data models, the core of your software. This core deals with things like accessing and saving data, manipulating numbers and the like. This functionality is usually bundled together to create the tools the software produces. In the case of ArcMap, a tool like buffer could use components about reading and writing data, coordinate transformation routines, and probably some sort of functionality that allows manipulation of spatial data. To bring it back to the geoprocessor, and why it is so much more powerful than using the software by itself, what you get access to is not only the tools ESRI has created for you by compiling multiple elements, but you also get access to a lot of those elements yourself that allows you to write your own buffer tool for example.</p>
<h3>Understanding what the Geoprocessor is</h3>
<p>When one talks about the geoprocessor, one is referring to a <a href="http://docs.python.org/tutorial/classes.html">Python object</a> built by ESRI, that allows one to call many different functions to perform operations. As in most Python code, the definitions of the object reside in a <a href="http://docs.python.org/tutorial/modules.html">module</a> that is provided to you. As with any other module, in order to access it through Python you need to import it. This is done by simply typing<em> import arcgisscripting</em> in your Python code.</p>
<pre class="brush: python; title: ;">
import arcgisscripting
# Imports the module provided by ESRI
</pre>
<p>In this case, the module provides a single command accessible to you called <em>create</em>. This exposed function allows one to instantiate the geoprocessor object. Simply calling the create() command is enough to return to you a geoprocessor object. You can also pass parameters to it, but the only one at the moment is the number 9.3, to create a geoprocessor object that returns values based on the 9.3 iteration of the programming model.</p>
<pre class="brush: python; title: ;">
gp = arcgisscripting.create(9.3)
# Instantiates the geoprocessor and assigns the name gp to it
</pre>
<h3>Beginning our Travel in the Geoprocessor Programming Model</h3>
<div id="attachment_186" class="wp-caption alignright" style="width: 210px"><img class="size-full wp-image-186" title="Geoprocessor Object" src="http://michalisavraam.org/wp-content/uploads/2009/10/arcgisscripting.png" alt="Geoprocessor Object" width="200" height="803" /><p class="wp-caption-text">Geoprocessor Object</p></div>
<p>The box on the right represents your geoprocessor. While it seems that these are the commands available to the<em> arcgisscripting</em> module, that is incorrect. Therefore, in the Geoprocessor Programming Model, one always enters through the cyan box, as seen on your right. There are few interesting things to note here:</p>
<ol>
<li>There are a lot of names appearing on the list.</li>
<li>Each name has a symbol ahead of it.</li>
<li>Most name have a parenthesis to their right.</li>
<li>A few of those names also have more information on the very right.</li>
</ol>
<p>Here is how one needs to interpret this part of the diagram. The symbols on the left define what the name represents.</p>
<h4>Geoprocessor Variables</h4>
<p>If there is a box connected to a dash, or two boxes, then the name represents a variable. What this means is that the name represents a value. There are a few options here:</p>
<ol>
<li><strong>Box on the left of the dash</strong>: This represents a built-in variable that is read-only. You as a user have no power to change these value, but can only read it. An example is the variable called <em>MessageCount</em>. The value represents how many messages the geoprocessor object has thus far.</li>
<li>Box on both sides of the dash: This represents a variable you can also write too. This is a value that the software can use, and you are allowed to overwrite it with your own value. An example is the <em>OverwriteOutput</em> variable, which allows you to tell the geoprocessor whether it has permission to overwrite existing files.</li>
</ol>
<p>Example usages for geoprocessor variables is below (click to expand):</p>
<pre class="brush: python; collapse: true; light: false; title: ; toolbar: true;">
import arcgisscripting
# Import the module provided by ESRI
gp = arcgisscripting.create(9.3)
# Instantiate the geoprocessor object

gp.OverwriteOutput = True
# Set the OverwriteOutput variable to True

print gp.MessageCount
# Print the number of messages on the object
</pre>
<h4>Geoprocessor methods</h4>
<p>Boxes are not the only symbols that appear on the dashes. There is also an arrow, which represents a function or procedure you are allowed to call. What this means is that by using that name, one is telling the geoprocessor to perform an operation. Some operations also allow you to define variables to be used on the operations. For example, <em>RemoveToolBox</em> is an operation that will remove a Toolbox from the geoprocessor, as long as you can provide its name. There are two types of operations available to you, and to distinguish them one needs to see what appears to the right of the name. here are the possibilities:</p>
<ol>
<li><strong>Methods that do not return anything</strong>: A lot of functions do not return anything to the user, and you can see this by the lack of any more information to the right of the name of the function. They perform an operation the user asks for, but do not return something the user can work with, other than a message of their success or a preset value. <em>ResetEnvironments()</em> is an example of such a method.</li>
<li><strong>Methods that return objects one can manipulate</strong>: Some of the functions in the list return a new object that the user can manipulate. These objects are often Python objects (like a Python List) that contain other ESRI objects, or sometimes an ESRI defined object directly that allows us to further manipulate what the software does. An example is the <em>InsertCursor()</em> method, that will return an object back called a <em>rows</em> object. The <em>ListFields()</em> method returns a Python List object populated with ESRI defined Field objects.</li>
</ol>
<p>The methods that return an object or a collection of objects also have an arrow on their right linking them with the object they return. For example, all the cursor methods connect to the row object to allow the user to see what that object provides. Similarly, the list methods oftentimes have an arrow to connect them to other objects, like the field object. The special case is the method called CreateObject(), which allows you to create a large set of objects from scratch, like spatial reference, points, valute table, etc.</p>
<p>Example usages of methods follow:</p>
<pre class="brush: python; title: ;">
 import arcgisscripting
 # Import the module provided by ESRI
 gp = arcgisscripting.create(9.3)
 # Instantiate the geoprocessor object

 gp.ResetEnvironments()
 # Reset all environments on the geoprocessor object

 tools = gp.ListTools()
 # Returns a Python list of all the tools available, save in the tools variable
for tool in tools:
print tool
# Loop through each tool and print it
 </pre>
<p>In the net part of this series I will investigate the objects connected with cursors (meaning the rows object and all connected object, like the row object (singular) and geometry).</p>
<h4>Geoprocessor Access to Tools</h4>
<p>The geoprocessor object also allows users to call on tools that ESRI provides. Those tools are identical to the tools found in the ArcToolbox. A list of them, with a description, is available from ESRI <a href="http://webhelp.esri.com/arcgisdesktop/9.3/pdf/Geoprocessing_Quick_Guide.pdf">here</a> (note, it is a large PDF file). Note that the Python scripting syntax is not included in that file, but the help file contains a Python example for each tool. You will need to search for it yourself unfortunately, but the thing one needs to remember is that the tool name remains the same, and all parameters to be passed to it must be within parenthesis.</p>
<p>I hope you enjoyed this article and be sure to visit for the remaining parts.</p>
Note: There is a rating embedded within this post, please visit this post to rate it.


<p>Related posts:<ol><li><a href='http://michalisavraam.org/2010/02/loading-the-geoprocessor-safely/' rel='bookmark' title='Permanent Link: Loading the Geoprocessor Safely'>Loading the Geoprocessor Safely</a></li>
</ol></p>]]></content:encoded>
			<wfw:commentRss>http://michalisavraam.org/2009/10/understanding-the-geoprocessor-programming-model-part/feed/</wfw:commentRss>
		<slash:comments>7</slash:comments>
		</item>
		<item>
		<title>Using the geoprocessor&#8217;s List* Methods</title>
		<link>http://michalisavraam.org/2009/08/using-the-geoprocessors-list-methods/</link>
		<comments>http://michalisavraam.org/2009/08/using-the-geoprocessors-list-methods/#comments</comments>
		<pubDate>Wed, 19 Aug 2009 20:58:26 +0000</pubDate>
		<dc:creator>Michalis Avraam</dc:creator>
				<category><![CDATA[GIS* Points]]></category>
		<category><![CDATA[Python Geoprocessing]]></category>
		<category><![CDATA[Python Points]]></category>
		<category><![CDATA[geoprocessing]]></category>
		<category><![CDATA[ListDatasets]]></category>
		<category><![CDATA[ListFeatureClasses]]></category>
		<category><![CDATA[ListFields]]></category>
		<category><![CDATA[ListRasters]]></category>
		<category><![CDATA[ListTables]]></category>
		<category><![CDATA[ListWorkspaces]]></category>
		<category><![CDATA[python]]></category>

		<guid isPermaLink="false">http://michalisavraam.org/?p=131</guid>
		<description><![CDATA[The geoprocessor object has multiple List methods one can use to retrieve lists of items that it is aware of. Below are examples of the most commonly encountered ones: ListWorkspaces(), ListTables(), ListRasters(), ListFeatureClasses(), ListDatasets() and ListFields(). ListWorkspaces() The purpose of ListWorkspaces() is to provide the user with a listing of the types of workspaces that <a href='http://michalisavraam.org/2009/08/using-the-geoprocessors-list-methods/'>[...]</a>


Related posts:<ol><li><a href='http://michalisavraam.org/2009/06/geoprocessing-iteration-with-python/' rel='bookmark' title='Permanent Link: Geoprocessing Iteration with Python'>Geoprocessing Iteration with Python</a></li>
</ol>]]></description>
			<content:encoded><![CDATA[<p>The geoprocessor object has multiple List methods one can use to retrieve lists of items that it is aware of. Below are examples of the most commonly encountered ones: ListWorkspaces(), ListTables(), ListRasters(), ListFeatureClasses(), ListDatasets() and ListFields().<br />
<span id="more-131"></span></p>
<h2>ListWorkspaces()</h2>
<p>The purpose of ListWorkspaces() is to provide the user with a listing of the types of workspaces that ArcGIS can make use of. The command is simple and accepts two parameters, a wildcard, and the type of workspace one is using. Below is a listing of the parameters:</p>
<table border="1" align="left">
<tbody>
<tr>
<td valign="top"><em>wildcard</em></td>
<td>OPTIONAL. A combination of the star character (*) and any number of characters to help limit results. For example, listing all workspaces with the word nature anywhere in the name would use a wildcard &#8220;*nature*&#8221;.</td>
</tr>
<tr>
<td valign="top"><em>Workspace Type</em></td>
<td>OPTIONAL. Limits the type of workspaces that are returned. Possible values are:</p>
<ul>
<li>Access: Only personal geodatabases are returned.</li>
<li>Coverage: Only coverage workspaces are returned.</li>
<li>FileGDB: Only file geodatabases are returned.</li>
<li>Folder: Only shapefile workspaces are returned.</li>
<li>SDE: Only SDE databases are returned.</li>
<li>ALL: Returns all above types of workspaces.</li>
</ul>
</td>
</tr>
</tbody>
</table>
<p>In order to execute the command, you also need to have your workspace defined. This may sounds a bit contradictory, as you are trying to find workspaces, but what this does is identify an initial location on the disk to start from.</p>
<h3>Sample ListWorkspaces() Code</h3>
<pre class="brush: python; title: ;">
import arcgisscripting
gp = arcgisscripting.create(9.3)    # We are using the 9.3 version here
gp.workspace = &quot;mydatafolder&quot;   # The original location the search begins at
accessWorkspaces = gp.ListWorkspaces(&quot;*&quot;, &quot;Access&quot;)   # Return all personal geodatabases type workspaces
coveraWorkspaces = gp.ListWorkspaces(&quot;*&quot;, &quot;Coverage&quot;)  # Return all coverages type workspaces
fileGDBWorkspaces = gp.ListWorkspaces(&quot;*&quot;, &quot;FileGDB&quot;)  # Return all file geodatabases type workspaces
folderWorkspaces = gp.ListWorkspaces(&quot;city*&quot;, &quot;Folder&quot;)  # Return all shapefile folders starting with the word &quot;city&quot;
sdeWorkspaces = gp.ListWorkspaces(&quot;*&quot;, &quot;SDE&quot;)    # Return all SDE type workspaces
allWorkspaces = gp.ListWorkspaces(&quot;*&quot;, &quot;ALL&quot;)   # Return all workspaces of all types
</pre>
<p>Please note that if you are using an earlier version of the geoprocessor (versions 9.2 and below), there are some slight changes on how you access the result of these commands. In 9.3 and above, results are Python Lists, while in earlier versions the results are a geoprocessing enumeration.</p>
<h2>ListTables()</h2>
<p>The purpose of ListTabless() is to provide the user with a listing of tables ina workspace. The command is simple and accepts two parameters, a wildcard, and the type of table one is seeking. Below is a listing of the parameters:</p>
<table border="1" align="left">
<tbody>
<tr>
<td valign="top"><em>wildcard</em></td>
<td>OPTIONAL. A combination of the star character (*) and any number of characters to help limit results. For example, listing all tables with the word event anywhere in the name would use a wildcard &#8220;*event*&#8221;.</td>
</tr>
<tr>
<td valign="top"><em>Table Type</em></td>
<td>OPTIONAL. Limits the type of tables that are returned. Possible values are:</p>
<ul>
<li>dBase: Only dBase (.dbf) tables are returned.</li>
<li>INFO: Only INFO tables are returned.</li>
<li>ALL: Returns all above types of tables.</li>
</ul>
</td>
</tr>
</tbody>
</table>
<p>In order to execute the command, you also need to have your workspace defined.</p>
<h3>Sample ListTables() Code</h3>
<pre class="brush: python; title: ;">
 import arcgisscripting
 gp = arcgisscripting.create(9.3)    # We are using the 9.3 version here
 gp.workspace = &quot;mydatafolder&quot;   # The original location the search begins at
 dbfTables = gp.ListTables(&quot;*&quot;, &quot;dBase&quot;)   # Return all dBase tables
infoTables = gp.ListTables(&quot;*&quot;, &quot;INFO&quot;)  # Return all INFO tables
allTables = gp.ListTables(&quot;*&quot;, &quot;ALL&quot;)   # Return all tables. This list is equal with the concatenation of the two above lists.
 </pre>
<p>Please note that if you are using an earlier version of the geoprocessor (versions 9.2 and below), there are some slight changes on how you access the result of these commands. In 9.3 and above, results are Python Lists, while in earlier versions the results are a geoprocessing enumeration.</p>
<h2>ListRasters()</h2>
<p>The purpose of ListRasters() is to provide the user with a listing of raster type datasets in a workspace. The command is simple and accepts two parameters, a wildcard, and the type of raster file one is seeking. Below is a listing of the parameters:</p>
<table border="1" align="left">
<tbody>
<tr>
<td valign="top"><em>wildcard</em></td>
<td>OPTIONAL. A combination of the star character (*) and any number of characters to help limit results. For example, listing all rasters with the word dem anywhere in the name would use a wildcard &#8220;*dem*&#8221;.</td>
</tr>
<tr>
<td valign="top"><em>Raster Type</em></td>
<td>OPTIONAL. Limits the type of raster files that are returned. Possible values are:</p>
<ul>
<li>BMP: Only bitmap image files are returned.</li>
<li>GIF: Only Graphic Interchange Format files are returned.</li>
<li>IMG: Only ERDAS IMAGINE files are returned.</li>
<li>JP2: Only JPEG 2000 raster image files are returned.</li>
<li>JPG: Only JPEG raster image files are returned.</li>
<li>PNG: Only Portable Network Graphics image files are returned.</li>
<li>TIFF: Only Tagged Image File Format files are returned.</li>
<li>GRID: Only ESRI GRID raster fles are returned.</li>
<li>ALL: Returns all above types of raster.</li>
</ul>
</td>
</tr>
</tbody>
</table>
<p>In order to execute the command, you also need to have your workspace defined.</p>
<h3>Sample ListRasters() Code</h3>
<pre class="brush: python; title: ;">
 import arcgisscripting
 gp = arcgisscripting.create(9.3)    # We are using the 9.3 version here
 gp.workspace = &quot;mydatafolder&quot;   # The original location the search begins at
bmpFiles = gp.ListRasters(&quot;*&quot;, &quot;BMP&quot;) # Return only BMP files
gifFiles = gp.ListRasters(&quot;*&quot;, &quot;GIF&quot;) # Return only GIF files
imgFiles = gp.ListRasters(&quot;*&quot;, &quot;IMG&quot;) # Return only IMG files
jp2Files = gp.ListRasters(&quot;*&quot;, &quot;JP2&quot;) # Return only JP2 files
jpgFiles = gp.ListRasters(&quot;*&quot;, &quot;JPG&quot;) # Return only JPG files
pngFiles = gp.ListRasters(&quot;*&quot;, &quot;PNG&quot;) # Return only PNG files
tiffFiles = gp.ListRasters(&quot;*&quot;, &quot;TIFF&quot;) # Return only TIFF files
gridFiles = gp.ListRasters(&quot;*&quot;, &quot;GRID&quot;) # Return only GRID files
allFiles = gp.ListRasters() # Returns all raster file type, since optional parameters not provided.
</pre>
<p>Please note that if you are using an earlier version of the geoprocessor (versions 9.2 and below), there are some slight changes on how you access the result of these commands. In 9.3 and above, results are Python Lists, while in earlier versions the results are a geoprocessing enumeration.</p>
<h2>ListFeatureClasses()</h2>
<p>The purpose of ListFeatureClasses() is to provide the user with a listing of feature classes in a workspace. The command is simple and accepts two parameters, a wildcard, and the type of feature class one is seeking. Below is a listing of the parameters:</p>
<table border="1" align="left">
<tbody>
<tr>
<td valign="top"><em>wildcard</em></td>
<td>OPTIONAL. A combination of the star character (*) and any number of characters to help limit results. For example, listing all feature classes ending with the &#8220;fc&#8221; characters in their name would use a wildcard &#8220;*fc&#8221;.</td>
</tr>
<tr>
<td valign="top"><em>Feature Class Type</em></td>
<td>OPTIONAL. Limits the type of feature classes that are returned. Possible values are:</p>
<ul>
<li>ANNOTATION: Only annotation feature classes are returned.</li>
<li>ARC: Only arc feature classes are returned.</li>
<li>DIMENSION: Only dimension feature classes are returned.</li>
<li>LABEL: Only label feature classes are returned.</li>
<li>LINE: Only line feature classes are returned.</li>
<li>NODE: Only node feature classes are returned.</li>
<li>POINT: Only point feature classes are returned.</li>
<li>POLYGON: Only polygon feature classes are returned.</li>
<li>REGION: Only region feature classes are returned.</li>
<li>ROUTE:  Only route feature classes are returned.</li>
<li>TIC: Only tic feature classes are returned.</li>
</ul>
</td>
</tr>
</tbody>
</table>
<p>In order to execute the command, you also need to have your workspace defined.</p>
<h3>Sample ListFeatureClasses() Code</h3>
<pre class="brush: python; title: ;">
 import arcgisscripting
 gp = arcgisscripting.create(9.3)    # We are using the 9.3 version here
 gp.workspace = &quot;mydatafolder&quot;   # The original location the search begins at

pointFCs = gp.ListFeatureClasses(&quot;*&quot;, &quot;POINT&quot;) # Return only Point feature classes
lineFCs = gp.ListFeatureClasses(&quot;*&quot;, &quot;LINE&quot;) # Return only Line feature classes
polygonFCs = gp.ListFeatureClasses(&quot;*&quot;, &quot;POLYGON&quot;) # Return only Polygon feature classes
# Similarly, change the type to one of the supported types listed above
</pre>
<p>Please note that if you are using an earlier version of the geoprocessor (versions 9.2 and below), there are some slight changes on how you access the result of these commands. In 9.3 and above, results are Python Lists, while in earlier versions the results are a geoprocessing enumeration.</p>
<h2>ListDatasets()</h2>
<p>The purpose of ListDatasets() is to provide the user with a listing of the datasets in a workspace that ArcGIS can make use of. The command is simple and accepts two parameters, a wildcard, and the type of dataset one is using. Below is a listing of the parameters:</p>
<table border="1" align="left">
<tbody>
<tr>
<td valign="top"><em>wildcard</em></td>
<td>OPTIONAL. A combination of the star character (*) and any number of characters to help limit results. For example, listing all datasets that begin with the word &#8220;my&#8221; would use a wildcard &#8220;my*&#8221;.</td>
</tr>
<tr>
<td valign="top"><em>Workspace Type</em></td>
<td>OPTIONAL. Limits the type of datasets that are returned. Possible values are:</p>
<ul>
<li>Feature: Geodatabase or Coverage datasets, depending on the type of workspace.</li>
<li>TIN: Only trianular irregular network datasets are returned..</li>
<li>Raster: Only raster datasets are returned.</li>
<li>CAD: Only CAD type datasets are returned.</li>
<li>ALL: Returns all above types of datasets.</li>
</ul>
</td>
</tr>
</tbody>
</table>
<p>In order to execute the command, you also need to have your workspace defined.</p>
<h3>Sample ListDatasets() Code</h3>
<pre class="brush: python; title: ;">
import arcgisscripting
gp = arcgisscripting.create(9.3)    # We are using the 9.3 version here
gp.workspace = &quot;myPersonalDB.mdb&quot;   # The original location the search begins at - a geodatabse
pgdbDatasets = gp.ListDatasets(&quot;*&quot;, &quot;Feature&quot;)   # Return all datasets of type Feature within a personal geodatabases
# Similarly, changing the workspace and type of dataset, one can retrieve a list of all datasets
</pre>
<p>Please note that if you are using an earlier version of the geoprocessor (versions 9.2 and below), there are some slight changes on how you access the result of these commands. In 9.3 and above, results are Python Lists, while in earlier versions the results are a geoprocessing enumeration.</p>
<h2>ListFields()</h2>
<p>The purpose of ListFields() is to provide the user with a listing of the fields within a table, shapefile or feature class that ArcGIS can make use of. The command is simple and accepts three parameters, an input table/shapefile/feature class, a wildcard, and the type of field one is trying to list. Below is a listing of the parameters:</p>
<table border="1" align="left">
<tbody>
<tr>
<td valign="top"><em>Input Table</em></td>
<td>REQUIRED: The input file to be used to read fields. Possible types of files accepted are:</p>
<ul>
<li>Table (dBase, INFO)</li>
<li>Shapefile (.shp)</li>
<li>Feature Class (any of the feature classes shown above in ListFeatureClasses)</li>
</ul>
</td>
</tr>
<tr>
<td valign="top"><em>wildcard</em></td>
<td>OPTIONAL. A combination of the star character (*) and any number of characters to help limit results. For example, listing all fields that begin with the word &#8220;Shape&#8221; would use a wildcard &#8220;Shape*&#8221;.</td>
</tr>
<tr>
<td valign="top"><em>Field Type</em></td>
<td>OPTIONAL. Limits the type of workspaces that are returned. Possible values are:</p>
<ul>
<li>SmallInteger: Only fields of Small Integer type are returned.</li>
<li>Integer: Only fields of Integer type are returned.</li>
<li>Single: Only fields of Single precision floating point are returned.</li>
<li>Double: Only fields of Double precision floating point are returned.</li>
<li>String: Only fields of String type are returned.</li>
<li>Date: Only fields of Date type are returned.</li>
<li>OID: Only fields of OID type are returned (internal Object IDentifier number).</li>
<li>Geometry: Only fields of Geometry type are returned.</li>
<li>BLOB:  Only fields of Binary Large OBject are returned.</li>
<li>ALL: Returns all above types of fields.</li>
</ul>
</td>
</tr>
</tbody>
</table>
<p>In order to execute the command, you also need to have your workspace defined. This may sounds a bit contradictory, as you are trying to find workspaces, but what this does is identify an initial location on the disk to start from.</p>
<h3>Sample ListFields() Code</h3>
<pre class="brush: python; title: ;">
import arcgisscripting
gp = arcgisscripting.create(9.3)    # We are using the 9.3 version here
gp.workspace = &quot;mydatafolder&quot;   # The original location the search begins at
fileToRead = &quot;myShape.shp&quot; # resides in the mydatafolder workspace
allFields = gp.ListFields(fileToRead, &quot;*&quot;, &quot;ALL&quot;) # List all fields in the fileToRead table
geoFields = gp.ListFields(fileToRead, &quot;*&quot;, &quot;Geometry&quot;) # List geometry fields in the fileToRead table
# Similarly, you can search and return any specific fields you need. This is often done when asked to add a field, to verify it does not exist.
fieldToAdd = &quot;Name&quot; # Give our field a name
# Check if the field exists
if len(gp.ListFields(fileToRead, fieldToAdd, &quot;ALL)) == 0:
    # If the field does not exist, the length of the returned list is zero
    # Within this loop, we know the fields does not exist, so we need to add it
    gp.AddField(fileToRead, fieldToAdd, &quot;TEXT&quot;, &quot;#&quot;, &quot;#&quot;, &quot;256&quot;)
    # The above line adds a string field called &quot;Name&quot; with 256 characters maximum length
</pre>
<p>Please note that if you are using an earlier version of the geoprocessor (versions 9.2 and below), there are some slight changes on how you access the result of these commands. In 9.3 and above, results are Python Lists, while in earlier versions the results are a geoprocessing enumeration.</p>
Note: There is a rating embedded within this post, please visit this post to rate it.


<p>Related posts:<ol><li><a href='http://michalisavraam.org/2009/06/geoprocessing-iteration-with-python/' rel='bookmark' title='Permanent Link: Geoprocessing Iteration with Python'>Geoprocessing Iteration with Python</a></li>
</ol></p>]]></content:encoded>
			<wfw:commentRss>http://michalisavraam.org/2009/08/using-the-geoprocessors-list-methods/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>Python Geoprocessing in ArcGIS 9.2 vs. 9.3</title>
		<link>http://michalisavraam.org/2009/07/python-geoprocessing-in-arcgis-9-2-vs-9-3/</link>
		<comments>http://michalisavraam.org/2009/07/python-geoprocessing-in-arcgis-9-2-vs-9-3/#comments</comments>
		<pubDate>Fri, 17 Jul 2009 07:20:39 +0000</pubDate>
		<dc:creator>Michalis Avraam</dc:creator>
				<category><![CDATA[GIS* Points]]></category>
		<category><![CDATA[Python Geoprocessing]]></category>
		<category><![CDATA[Python Points]]></category>
		<category><![CDATA[9.2]]></category>
		<category><![CDATA[9.2 vs. 9.3]]></category>
		<category><![CDATA[9.3]]></category>
		<category><![CDATA[ArcGIS]]></category>
		<category><![CDATA[arcgisscripting]]></category>
		<category><![CDATA[geoprocessing]]></category>
		<category><![CDATA[python]]></category>

		<guid isPermaLink="false">http://michalisavraam.org/?p=86</guid>
		<description><![CDATA[There are some fundamental differences between geoprocessing performed in ArcGIS version 9.2 and 9.3. While I will not cover them all in this post, I will attempt to show the most fundamental differences that people seem to encounter more often. The fundamental differences are as follows: The method of invoking the geoprocessor is very similar <a href='http://michalisavraam.org/2009/07/python-geoprocessing-in-arcgis-9-2-vs-9-3/'>[...]</a>


Related posts:<ol><li><a href='http://michalisavraam.org/2009/06/geoprocessing-iteration-with-python/' rel='bookmark' title='Permanent Link: Geoprocessing Iteration with Python'>Geoprocessing Iteration with Python</a></li>
</ol>]]></description>
			<content:encoded><![CDATA[<p>There are some fundamental differences between geoprocessing performed in ArcGIS version 9.2 and 9.3. While I will not cover them all in this post, I will attempt to show the most fundamental differences that people seem to encounter more often.<br />
<span id="more-86"></span><br />
The fundamental differences are as follows:</p>
<ol>
<li>The method of invoking the geoprocessor is very similar for both, with the exception of an optional parameters when creating the object.</li>
<li>Geoprocessing methods do not return Python built-in data types but rather ESRI iterable objects.</li>
<li>Methods that used to return True/False values now return the Python True or False object rather than a string or 0/1.</li>
</ol>
<p>The following table illustrates the differences:</p>
<table border="0">
<tbody>
<tr>
<th> ArcGIS version 9.2</th>
<th> ArcGIS version 9.3</th>
</tr>
<tr>
<td>
<pre class="brush: python; title: ;">
gp = arcgisscripting.create()
</pre>
</td>
<td valign="top">
<pre class="brush: python; title: ;">
gp = arcgisscripting.create(9.3)
</pre>
</td>
</tr>
<tr>
<td>
<pre class="brush: python; title: ;">
# Create a list of available feature classes
fcs = gp.ListFeatureClasses()
# Iterate through said feature classes
fcs.Reset()
fc = fcs.Next()
while fc:
    # Do work here
    fc = fcs.Next()
</pre>
</td>
<td valign="top">
<pre class="brush: python; title: ;">
# Create a list of available feature classes
fcs = gp.ListFeatureClasses()
# Iterate through said feature classes
for fc in fcs:
    # Do work here
</pre>
</td>
</tr>
<tr>
<td>
<pre class="brush: python; title: ;">
# Identify the fields of a feature class
dsc = gp.describe(fc)
# Get the fields from the description
flds = dsc.Fields
# Iterate through the fields
flds.Reset()
field = flds.Next()
while field:
    # Do work here
    field = flds.Next()
</pre>
</td>
<td valign="top">
<pre class="brush: python; title: ;">
# Identify the files of a feature class
dsc = gp.describe(fc)
# Get the fields from the description
flds = dsc.Fields
# Iterate through the fields
for field in flds:
    # Do work here
</pre>
</td>
</tr>
<tr>
<td>
<pre class="brush: python; title: ;">
# Tell the geoprocessor to overwrite output by default.
gp.OverWriteOutput = 1
</pre>
</td>
<td>
<pre class="brush: python; title: ;">
# Tell the geoprocessor to overwrite output by default
gp.OverWriteOutput = True
</pre>
</td>
</tr>
</tbody>
</table>
<p>There is not list of commands that need the changes to the best of my knowledge. But a quick look through the <a href="http://webhelp.esri.com/arcgisdesktop/9.2/pdf/Geoprocessor.pdf">Geoprocessor Programming Model for ArcGIS 9.2</a> can show which methods return an enumeration unit. In brief, ListDatasets, ListFeatureClasses, ListRasters, ListTables, ListWorkspaces, ListEnvironments, ListToolboxes, ListTools and all other methods that return an Array Object. For a complete listing of the changes, please read the ESRI document for <a href="http://webhelp.esri.com/arcgisdesktop/9.3/index.cfm?TopicName=Differences_between_geoprocessor_versions">Geoprocessor changes in 9.3</a>.</p>
Note: There is a rating embedded within this post, please visit this post to rate it.


<p>Related posts:<ol><li><a href='http://michalisavraam.org/2009/06/geoprocessing-iteration-with-python/' rel='bookmark' title='Permanent Link: Geoprocessing Iteration with Python'>Geoprocessing Iteration with Python</a></li>
</ol></p>]]></content:encoded>
			<wfw:commentRss>http://michalisavraam.org/2009/07/python-geoprocessing-in-arcgis-9-2-vs-9-3/feed/</wfw:commentRss>
		<slash:comments>2</slash:comments>
		</item>
		<item>
		<title>Manipulating Excel files using Python part 2: Writing Excel Files</title>
		<link>http://michalisavraam.org/2009/06/manipulating-excel-files-using-python-part-2-writing-files/</link>
		<comments>http://michalisavraam.org/2009/06/manipulating-excel-files-using-python-part-2-writing-files/#comments</comments>
		<pubDate>Thu, 18 Jun 2009 04:50:18 +0000</pubDate>
		<dc:creator>Michalis Avraam</dc:creator>
				<category><![CDATA[Python Points]]></category>
		<category><![CDATA[data manipulation]]></category>
		<category><![CDATA[excel]]></category>
		<category><![CDATA[excel files]]></category>
		<category><![CDATA[python]]></category>
		<category><![CDATA[write]]></category>
		<category><![CDATA[writing]]></category>
		<category><![CDATA[xlwd]]></category>

		<guid isPermaLink="false">http://michalisavraam.org/blog/38-blog-entries/58-writing-excel-files-using-python-no-excel-needed</guid>
		<description><![CDATA[Writing Excel files using Python is quite easy, using the xlwt package. Similar to xlrd mentioned in an earlier post, xlwt allows one to write Excel files from scratch using Python.A brief reminded of Excel files (as mentioned in an earlier post) follows, to help people understand how Excel files work.The program stores data in <a href='http://michalisavraam.org/2009/06/manipulating-excel-files-using-python-part-2-writing-files/'>[...]</a>


Related posts:<ol><li><a href='http://michalisavraam.org/2009/06/manipulating-excel-files-using-python-part-1-reading-files/' rel='bookmark' title='Permanent Link: Manipulating Excel files using Python part 1: Reading Excel Files'>Manipulating Excel files using Python part 1: Reading Excel Files</a></li>
</ol>]]></description>
			<content:encoded><![CDATA[<p style="text-align: left;">Writing Excel files using Python is quite easy, using the <a title="xwt repository" href="https://secure.simplistix.co.uk/svn/xlwt/trunk/">xlwt package</a>. Similar to <a title="xlrd package" href="http://www.lexicon.net/sjmachin/xlrd.htm">xlrd</a> mentioned in an <a title="Reaing Excel files using Python" href="http://michalisavraam.org/blog/38-blog-entries/57-manipulating-excel-files-in-python-no-excel-needed.html">earlier post</a>, xlwt allows one to write Excel files from scratch using Python.<span id="more-22"></span><img class="alignright size-full wp-image-43" title="excelPreview" src="http://michalisavraam.org/wp-content/uploads/2009/06/excelPreview.png" alt="excelPreview" width="461" height="280" />A brief reminded of Excel files (as mentioned in an earlier post) follows, to help people understand how Excel files work.The program stores data in what is called a <strong>Workbook</strong>. Think of this as the file on your computer (the .xls). A Workbook can then have one or more <strong>Sheets</strong>, the little tabs on the bottom left corner usually. Within each Sheet, you can find an arrangement of <strong>Cells</strong> in a matrix form, which are referenced by Column Name and Row Number (so the top left cell is A1, the one directly to its right is A2, the one below is B2, etc. The image should help shed some light if you are not familiar with the concept of spreadsheets.To create your own Excel files using Python, all you need to have is the xlwt package. The workflow for such a process is simple: create a workbook, create a sheet within the workbook, start writing data into the cells of the sheet. Sample code shown below should help you get started quickly and easily.</p>
<pre style="text-align: left;">
<pre class="brush: python; title: ;">
import xlwt # Import the package
wbook = xlwt.Workbook() # Create a new workbook
sheet = wbook.add_sheet(&amp;amp;amp;quot;Sample Sheet&amp;amp;amp;quot;) # Create a sheet
data = &amp;amp;amp;quot;Sample data&amp;amp;amp;quot; # Something to write into the sheet
for rowx in range(5):
# Loop through the first five rows
for colx in range(5):
# Loop through the first five columns
# Write the data to rox, column
sheet.write(rowx, colx, data)
# Save our workbook on the harddrive
wbook.save(&amp;amp;amp;quot;myFile.xls&amp;amp;amp;quot;)</pre>
</pre>
<p>And that is all you need. You just created a brand new Excel file called myFile.xls within Python without the use of Excel itself. The file has the first 5 rows and columns filled out with the text &#8220;Sample data&#8221;. It is trivial then to change this so it can save any data you want with a little bit more of Python.</p>
Note: There is a rating embedded within this post, please visit this post to rate it.


<p>Related posts:<ol><li><a href='http://michalisavraam.org/2009/06/manipulating-excel-files-using-python-part-1-reading-files/' rel='bookmark' title='Permanent Link: Manipulating Excel files using Python part 1: Reading Excel Files'>Manipulating Excel files using Python part 1: Reading Excel Files</a></li>
</ol></p>]]></content:encoded>
			<wfw:commentRss>http://michalisavraam.org/2009/06/manipulating-excel-files-using-python-part-2-writing-files/feed/</wfw:commentRss>
		<slash:comments>3</slash:comments>
		</item>
		<item>
		<title>Manipulating Excel files using Python part 1: Reading Excel Files</title>
		<link>http://michalisavraam.org/2009/06/manipulating-excel-files-using-python-part-1-reading-files/</link>
		<comments>http://michalisavraam.org/2009/06/manipulating-excel-files-using-python-part-1-reading-files/#comments</comments>
		<pubDate>Tue, 16 Jun 2009 05:42:21 +0000</pubDate>
		<dc:creator>Michalis Avraam</dc:creator>
				<category><![CDATA[Python Points]]></category>
		<category><![CDATA[data manipulation]]></category>
		<category><![CDATA[excel]]></category>
		<category><![CDATA[excel file]]></category>
		<category><![CDATA[python]]></category>
		<category><![CDATA[read]]></category>
		<category><![CDATA[reading]]></category>
		<category><![CDATA[xlrd]]></category>

		<guid isPermaLink="false">http://michalisavraam.org/blog/38-blog-entries/57-manipulating-excel-files-in-python-no-excel-needed</guid>
		<description><![CDATA[It is often the case that the freely available data online are in Excel format. If one has Excel, then one has the ability to do some sort of basic manipulation of the files. But if Excel is not available, or your analysis software does not read Excel files, there is another way: use Python <a href='http://michalisavraam.org/2009/06/manipulating-excel-files-using-python-part-1-reading-files/'>[...]</a>


Related posts:<ol><li><a href='http://michalisavraam.org/2009/06/manipulating-excel-files-using-python-part-2-writing-files/' rel='bookmark' title='Permanent Link: Manipulating Excel files using Python part 2: Writing Excel Files'>Manipulating Excel files using Python part 2: Writing Excel Files</a></li>
</ol>]]></description>
			<content:encoded><![CDATA[<p>It is often the case that the freely available data online are in Excel format. If one has Excel, then one has the ability to do some sort of basic manipulation of the files. But if Excel is not available, or your analysis software does not read Excel files, there is another way: use Python to manipulate Excel files.<span id="more-23"></span></p>
<p><img class="alignright size-full wp-image-43" title="excelPreview" src="http://michalisavraam.org/wp-content/uploads/2009/06/excelPreview.png" alt="excelPreview" width="461" height="280" />Before continuing, let&#8217;s discuss the basic idea of Excel. This programs stores data in what is called a <strong>Workbook</strong>. Think of this as the file on your computer (the .xls). A Workbook can then have one or more <strong>Sheets</strong>, the little tabs on the bottom left corner usually. Within each Sheet, you can find an arrangement of <strong>Cells</strong> in a matrix form, which are referenced by Column Name and Row Number (so the top left cell is A1, the one directly to its right is A2, the one below is B2, etc. The image should help shed some light if you are not familiar with the concept of spreadsheets.</p>
<p>In order to <strong>read</strong> Excel sheets in Python without using any Microsoft Office code, we need to use the excellent <a title="xlrd Package Website" href="http://www.lexicon.net/sjmachin/xlrd.htm">xlrd packge</a> by <a title="Lingfo Website" href="http://www.lexicon.net/sjmachin/">Lingfo</a>. The basic workflow is as follows:</p>
<ol>
<li>Open a workbook using <em>book = xlrd.open_workbook(&#8220;filetoread.xls&#8221;)</em></li>
<li>Access a sheet in the workbook using <em>sheet = book.sheet_by_index(0)</em> to open the first sheet, or if you know the name, <em>sheet = book.sheet_by_name(&#8220;Name of Sheet&#8221;)</em></li>
<li>Retrieve data using any of the multiple methods: <em>cellValue =sheet.cell_value(rowx, colx)</em>, or to retrieve a whole column use <em>colValues = sheet.col_values(colx, start_rowx=0, end_rowx=None)</em> or the retrieve a whole row use <em>rowValues = sheet.row_values(rowx, start_colx=0, end_colx=None)</em></li>
</ol>
<p>The basic idea is very simple, and we can easily write a little Python script that will allow us to read Excel files without the need to use Excel itself. The following example will offer a preview of an Excel file&#8217;s first sheet using the first 5 rows and columns of a file.</p>
<pre class="brush: python; title: ;">
import xlrd # Import the package
book = xlrd.open_workbook(&amp;amp;amp;quot;sample.xls&amp;amp;amp;quot;) # Open an .xls file
sheet = book.sheet_by_index(0) # Get the first sheet
for counter in range(5): # Loop for five times
# grab the current row
rowValues = sheet.row_values(counter,start_col=0, end_colx=4)
# Print the values of the row formatted to 10 characters wide
print &amp;amp;amp;quot;%-10s | %-10s | %-10s | %-10s | %-10s&amp;amp;amp;quot; % tuple(rowValues)
# Print row separator
print &amp;amp;amp;quot;-&amp;amp;amp;quot; *62
</pre>
<p>That is all there is to it. Quick, fast and no need for Excel whatsoever. Sample output is presented below:</p>
<p><img class="aligncenter size-full wp-image-46" title="sampleOutput" src="http://michalisavraam.org/wp-content/uploads/2009/06/sampleOutput.png" alt="sampleOutput" width="585" height="447" /></p>
Note: There is a rating embedded within this post, please visit this post to rate it.


<p>Related posts:<ol><li><a href='http://michalisavraam.org/2009/06/manipulating-excel-files-using-python-part-2-writing-files/' rel='bookmark' title='Permanent Link: Manipulating Excel files using Python part 2: Writing Excel Files'>Manipulating Excel files using Python part 2: Writing Excel Files</a></li>
</ol></p>]]></content:encoded>
			<wfw:commentRss>http://michalisavraam.org/2009/06/manipulating-excel-files-using-python-part-1-reading-files/feed/</wfw:commentRss>
		<slash:comments>3</slash:comments>
		</item>
		<item>
		<title>Geoprocessing Iteration with Python</title>
		<link>http://michalisavraam.org/2009/06/geoprocessing-iteration-with-python/</link>
		<comments>http://michalisavraam.org/2009/06/geoprocessing-iteration-with-python/#comments</comments>
		<pubDate>Fri, 12 Jun 2009 02:05:05 +0000</pubDate>
		<dc:creator>Michalis Avraam</dc:creator>
				<category><![CDATA[GIS* Points]]></category>
		<category><![CDATA[Python Geoprocessing]]></category>
		<category><![CDATA[Python Points]]></category>
		<category><![CDATA[arcgisscripting]]></category>
		<category><![CDATA[geoprocessing]]></category>
		<category><![CDATA[iteration]]></category>
		<category><![CDATA[ListDatasets]]></category>
		<category><![CDATA[ListFeatureClasses]]></category>
		<category><![CDATA[ListWorkspaces]]></category>
		<category><![CDATA[python]]></category>

		<guid isPermaLink="false">http://michalisavraam.org/teaching/36-pygeoprocessing/56-geoprocessing-iteration-with-python</guid>
		<description><![CDATA[There are multiple problems analysts face when they have to deal with processing multiple data files. There is the issue of identifying similarities and commonalities in files, and then of course how to automate the processing so they don&#8217;t have to run a program multiple times with the same parameters of separate files. In the <a href='http://michalisavraam.org/2009/06/geoprocessing-iteration-with-python/'>[...]</a>


Related posts:<ol><li><a href='http://michalisavraam.org/2009/08/using-the-geoprocessors-list-methods/' rel='bookmark' title='Permanent Link: Using the geoprocessor&#8217;s List* Methods'>Using the geoprocessor&#8217;s List* Methods</a></li>
</ol>]]></description>
			<content:encoded><![CDATA[<p>There are multiple problems analysts face when they have to deal with processing multiple data files. There is the issue of identifying similarities and commonalities in files, and then of course how to automate the processing so they don&#8217;t have to run a program multiple times with the same parameters of separate files. In the world of ESRI&#8217;s GIS analysis, this can be performed quite easily with the help of Geoprocessing, either in Python or the Model Builder. Below is sample code that allows the iteration over a number of datasets.<span id="more-18"></span></p>
<p>Geoprocessing in Python provides multiple methods that can help one iterate. Depending on the dataset types you have, you can access list of data easily and effortlessly. The following code will show you how this is done in version 9.3, although earlier versions are as easy to use as well.</p>
<p>In order to iterate a process, we need a list of files we will use, and then a series of commands to be run on those files. There are multiple ways to achieve this through the operating system (os and sys modules), but since we do have that pesky little problem of shapefiles having multiple files associated with them, or geodatabases being a single representation for the OS, we need a different solution. And here lies the power of the geoprocessor. It allows one to list data the way ESRI can recognize them: workspaces, (feature) datasets, feature classes, tables and rasters. So let&#8217;s begin.</p>
<p>Oftentimes, analysts store data in folders. If you are conducting a study in 10 different regions, it is often the case you save the data files for each region in a different folder. A folder structure like the following is common:</p>
<ul>
<li>\myStudy\</li>
<li>\myStudy\region1\</li>
<li>\myStudy\region2\</li>
<li>\myStudy\region3\</li>
<li>&#8230;</li>
</ul>
<p>We therefore need a method that allows us to go into the master folder (\myStudy\ in this case) and read the files in each folder. To achive this, we will read the names of folders first. The command <strong>ListWorkspaces(widcard, type)</strong> can help us do that, by accepting a wildcard as a first argument (any combination of * can help narrow things down) and the type of workspace we want (from Access, Coverage, FileGDB Folder, SDE or ALL). An example follows:</p>
<pre class="brush: python; title: ;">
import arcgisscripting # Import the geoprocessor capabilities
gp = arcgisscripting.create(9.3) # Create the geoprocessor object
masterFolder = r&quot;path\to\folder&quot; # Define the master folder
gp.workspace = masterFolder # Define the location to run the commands on
workspaces = gp.ListWorkspaces(&quot;*&quot;, &quot;Folder&quot;) # List all FOLDERS in master workspace
for workspace in workspaces: # Iterate through the workspaces one at a time
print workspace # Print the workspace name
# Do you work here
</pre>
<p>At this point, you have a Python list object that holds the names of all the subfolders that you may want to use. The next step is to identify a list of all data within that folder. To achieve that, we use one of the following commands, depending on the type of data we have: <strong>ListDatasets(wildcard, type)</strong>, <strong>ListFeatureClasses(wildcard, type)</strong>, <strong>ListTables(wildcard, type)</strong> or <strong>ListRasters(wildcard, type)</strong>. The wildcard is defined as above, but the type is different. Type actually refers to the type of listing. For datasets, the type is feature,TIN, raster, CAD or ALL. For feature classes the types are Annotation, arc, dimension, label, line, node, point, polygon, region, route or tic. Table types can be DBF, INFO or ALL. Similarly, raster types can be BMP, GIF, IMG, JP2, JPG, PNG, TIFF, GRID or ALL. We will contnue our example by searching for feature classes (shapefiles) in the folders we identified above.</p>
<pre class="brush: python; title: ;">
import arcgisscripting # Import the geoprocessor capabilities
gp = arcgisscripting.create(9.3) # Create the geoprocessor object
masterFolder = r&quot;path\to\folder&quot; # Define the master folder
gp.workspace = masterFolder # Define the location to run the commands on
workspaces = gp.ListWorkspaces(&quot;*&quot;, &quot;Folder&quot;) # List all FOLDERS in master workspace
for workspace in workspaces: # Iterate through the workspaces one at a time
gp.workspace = workspace # Change to the new workspace
fcs = gp.ListFeatureClasses() # No parameter defaults to all
for fc in fcs: # Iterate through each file in the folder now
print fc # print the feature class
# Do individual file work here
</pre>
<p>As you can see we managed to begin with a master folder and continue to analyze individual files within all subfolders of the initial master folder. This is all done in a few lines of code, minimize complexity and confussion for us. In less that 6 lines of Python code you can begin processing each file in your computer quickly and easily.</p>
<p>While listing of other types of files has not been shown, it is quite easy to do by using the appropriate command (as mentioned above). Dealing with databases is similar, as you can imagine and use the database as your master folder. Do not forget that &#8220;subfolders&#8221; in the database are called datasets, so you will need to use ListDatasets() instead of ListWorkspaces().</p>
<p>I hope this will be useful to some of you out there.</p>
Note: There is a rating embedded within this post, please visit this post to rate it.


<p>Related posts:<ol><li><a href='http://michalisavraam.org/2009/08/using-the-geoprocessors-list-methods/' rel='bookmark' title='Permanent Link: Using the geoprocessor&#8217;s List* Methods'>Using the geoprocessor&#8217;s List* Methods</a></li>
</ol></p>]]></content:encoded>
			<wfw:commentRss>http://michalisavraam.org/2009/06/geoprocessing-iteration-with-python/feed/</wfw:commentRss>
		<slash:comments>5</slash:comments>
		</item>
	</channel>
</rss>

