[GIS] Looping based on a spreasheet using python (in ArcGIS 9.3)

arcgis-9.3python

Here's what I am trying to do: I want to move feature classes from one .gdb (OLD) to another (NEW), but only the feature classes that are present in an excel spreadsheet.

  1. read from excel spreasheet (old name column)
  2. compare to old .gdb feature classes to find match
  3. move matched feature class to new .gdb
  4. rename feature class in new .gdb based on new name in excel spreadsheet (new name column)
  5. continue doing the above until the end of the spread sheet

Best Answer

Assuming you have the pyodbc library installed (there's an installer for Python 2.5 in their Downloads section) it's a simple matter of looping through each row of the Excel sheet. Something like:

#import libraries
import arcgisscripting
import pyodbc
import os.path

#set paths to documents
old_gdb = "path_to_old.gdb"
new_gdb = "path_to_new.gdb"
excel_path = "path_to.xls"

#initialise arcgis
gp = arcgisscripting.create(9.3)

#create a connection to the excel sheet
conn = pyodbc.connect('DRIVER={Microsoft Excel Driver (*.xls, *.xlsx, *.xlsm, *.xlsb)};DBQ=%s;Readonly=1' % excel_path, autocommit=True)

#**
#Create the cursor
#**
cursor = conn.cursor()

#Loop over all the rows returned from a cursor execute
for row in cursor.execute('select * from "Sheet1$"'):
    #we can reference columns by their name in the row object
    if gp.Exists(os.path.join(old_gdb, row.old_name_column)):
        gp.copy_management(os.path.join(old_gdb, row.old_name_column), os.path.join(new_gdb, row.new_name_column))
    else:
        print "Some warning"

If you don't want to use pyodbc, it should be easy enough to substitute in a csv reader or otherwise instead of the connection to the .xls. Good luck!

Related Question