Friday, 18 November 2016

arcpy - Updating attribute information


I need to write a script that updates the "LOCALITY" field in a feature class if it is empty with the suburb it is in.


I have identified the number of properties with select by location and the below script will show that 1340 properties in the first index of the localityList will need to be updated.


PyScripter says that the script runs ok but when I check the attribute table in ArcMap the LOCALITY field has not been updated.


How can I implement the update tool correctly? After that is done all I will need to do is loop through the localityList to move through all of the suburbs.


# Import modules
import arcpy

import os

#Set workspace geodatabase
arcpy.env.workspace = "C:\Users\Harry\Documents\Uni\Semester 1 2016\GIS3407 GIS Programming and Visualisation\Assignment 2\Assignment2.gdb"

# Create a list of suburbs
# Create an empty list
localityList = []
#Create the search cursor
rows = arcpy.SearchCursor("TWB_Suburbs")

#Move to the first row
row = rows.next()
#Append the list with the selected locality name
while row:
localityList.append(str(row.ADMINAREA))
#Move to the next row
row = rows.next()

print(str(len(localityList)) + " <-- # of suburbs")
del row, rows

# Make a layer of all of the properties with no locality value
# Create query
nullQuery = '"LOCALITY" = \' \''
# Create layer
nullLayer = arcpy.MakeFeatureLayer_management("TWB_Property", "TWB_Property_Layer", nullQuery)

# Select by location
indexCounter = 0
localityQuery = '"ADMINAREA" = ' + '\''+ localityList[indexCounter] + '\''
localityLayer = arcpy.MakeFeatureLayer_management("TWB_Suburbs", "TWB_Sububs_Layer", localityQuery)

arcpy.SelectLayerByLocation_management("TWB_Property_Layer", "WITHIN", "TWB_Sububs_Layer")

parcelList = []
rows = arcpy.SearchCursor("TWB_Property_Layer")
row = rows.next()

while row:
parcelList.append(row.OBJECTID)
row = rows.next()


print str(len(parcelList))

numberParcel = len(parcelList)

for parcel in range(0, numberParcel):
rows = arcpy.UpdateCursor("TWB_Property", '"LOCALITY" = ' + "'" + localityList[indexCounter] + "'")
row = rows.next()

row.setValue("LOCALITY", str(localityList[indexCounter]))
rows.next()


del row, rows

arcpy.Delete_management("TWB_Property_Layer")
arcpy.Delete_management("TWB_Sububs_Layer")

Answer



You need to include rows.updateRow(row) to save your changes to each row of your Update Cursor:


row.setValue("LOCALITY", str(localityList[indexCounter]))
rows.updateRow(row) # save the change to the row
rows.next()


However you should also take note of the comments above about using the arcpy.da.UpdateCursor and about how you've named both your SearchCursor and UpdateCursor to use rows and row.


No comments:

Post a Comment

arcpy - Changing output name when exporting data driven pages to JPG?

Is there a way to save the output JPG, changing the output file name to the page name, instead of page number? I mean changing the script fo...