hashbrown

Attributing Railways with Surrounding Population

Discussion created by hashbrown on Sep 6, 2011
Latest reply on Sep 14, 2011 by mnakleh
Hi,

I???ve tried to write a script to take a file of railway lines and find the towns within 2 kilometres of each railway line, sum the populations of those selected towns and return the result to a field in the railway lines file.

I???ve been successful in getting bits of the script to work in isolation (copied from other???s scripts), but not as a whole.  The script is below and I would really appreciate it if anyone can offer advice as to why it doesn???t work, or how it could be improved.

I only have an ArcView license (9.3.1) with Python 2.5 and I'm very new to Python.

Thank you,
Ash

# Import system modules
import sys, string, os, arcgisscripting

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

# Load required toolboxes.
gp.AddToolbox("C:/Program Files/ArcGIS/ArcToolbox/Toolboxes/Data Management Tools.tbx")

# Script arguments...
inFC = r"c:\data\Towns.shp"         # Input towns.
inFCSel = r"c:\data\railways.shp"      # Input railways.

# Local variables...
tempLayer = "tempLayer" # the towns
tempLayer2 = "tempLayer2" # the Railways
counter = 0

try:
    # Process: Make Feature Layer for input feature class (the towns).
    gp.MakeFeatureLayer_management(inFC, tempLayer, "", "", "")
        
    # Process: Make Feature Layer for Selecting features (the railways).
    gp.MakeFeatureLayer_management(inFCSel, tempLayer2, "", "", "")
    
    # Create a row and rows object to update the field (Railways).
    rows = gp.UpdateCursor(tempLayer2)
    row = rows.Next()

    # Iteration to loop through the railways
    while row:
        query = "\"FID\" = " + str(counter)

        # Process: Select the railway
        gp.SelectLayerByAttribute_management(tempLayer2, "NEW_SELECTION", query)
        
        # Process: Select towns within 2kms of the railway
        tempLayer3 = gp.SelectLayerByLocation_management(tempLayer, "WITHIN_A_DISTANCE", tempLayer2, "2 Kilometers" , "NEW_SELECTION")

        # Create row and rows object to sum the population (Towns).
        rows2 = gp.SearchCursor(tempLayer3)
        row2 = rows2.Next()
        rsum = 0

        # Iteration to loop through the selected towns
        while row2:
            rsum = rsum + row2.GetValue("Total_pop") # Sum the populations of the selected towns
            row2 = rows2.Next()
        
        row.SetValue("Pop_Sum",rsum)
        rows.UpdateRow(row) # update the population field for the selected railway

        counter = counter + 1
        row = rows.Next()
        
    gp.AddMessage("Processing done...")   

    # release locks...    
    del row
    del rows
    del row2
    del rows2
    del gp        
except:
    print "Error found.."
    gp.AddMessage("Error found..")
    print gp.getmessage(2)
    del tempLayer
    del tempLayer2
    del tempLayer3
    del gp

Outcomes