Monday, 6 June 2016

python - How to update feature class by iterating through values with branching?


I'm really struggling with getting this to work. Basically, I want my script to get the "newID" value and use that as a look up value. If the "newID" is found in the OldID list then do one thing, else do something else. The problem I'm having is it only grabs the first ID value and then does loops the rest of the code based on whatever category the first ID fell under. I need it to get the value of each field in the new data table, and write it to the corresponding field in the old data table. It does this just fine, but obviously it isn't checking the ID's after the first one, or updating/appending the geometry.


Here's what I've got so far. Just showing applicable code....


rows = gp.SearchCursor(new_data)
row = rows.next()

while row:
newID = row.getValue('ID')

newShape = row.SHAPE
y = 0

while newID in OldID_List:
gp.AddMessage('')
print 'Starting the updating for ratios'
where = 'ID' + ' = ' + str(newID)
new_rows = gp.UpdateCursor(old_data, where)
new_row = new_rows.next()


while y <= len(Field_List): # checks to see if ID exists -
# this means just update
for each in Field_List:
newValue = row.getValue(each)

if newValue is None:
new_row.setValue(str(each), 0)
else:
new_row.setValue(str(each), str(newValue))


y += 1

if y > len(Field_List):
new_row.Shape = newShape
new_rows.UpdateRow(new_row)
new_row = new_rows.next()
row = rows.next()
newID = row.getValue('ID')
newShape = row.SHAPE
y = 0


while newID not in OldID_List: # these are new objects to be appended
flag = 1
nsert_Rows = gp.InsertCursor(old_data)
nsert_Row = nsert_Rows.NewRow()

while y <= len(Field_List):
for each in Field_List:
newValue = row.getValue(each)
print 'Starting appends'


if newValue is None:
nsert_Row.setValue(str(each), 0)
else:
nsert_Row.setValue(str(each), str(newValue))

y += 1
if y > len(Field_List):
nsert_Row.ID = newID
nsert_Row.Shape = newShape

nsert_Rows.insertrow(nsert_Row)

row = rows.next()
newID = row.getValue('ID')
newShape = row.SHAPE

appends += 1
y = 0
del rows
del new_rows

if flag == 1:
del nsert_Rows

Any help or suggestions would be appreciated.


Thanks.



Answer



Inside of your inner-most loop, you are setting y=0. This prevents your code from ever escaping the while y <= len(Field_List): loop. As soon as y <=len(Field_List) goes to false, you reset y=0. This causes the previous statemen to go back to true and the loop to repeat.


You need to move this block of code outside of the while loop:


                      if y > len(Field_List):
new_row.Shape = newShape

new_rows.UpdateRow(new_row)
new_row = new_rows.next()
row = rows.next()
newID = row.getValue("ID")
newShape = row.SHAPE
y = 0

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...