0

I have a question for a current assignment that requires me to write a script that will add a new field to a feature class and then use a cursor to populate the new field by concatenating five other fields (name, address, city, stateabb, zipCode). The new field is FullAdd and will be the full mailing address in one field from the information that is already in the table.

I need help with the update cursor part of my code.

How do I make it write the concatenation to the new field?

I've tried so many things after the 'with cursor' statement and for loop and have no idea where to go next!

import arcpy
from arcpy import env
env.workspace = r"C:\mygdb.gdb"
env.overwriteOutput = True
# Set up search cursor for hospitals FC
# Make the hospitals FC a lyr
arcpy.MakeFeatureLayer_management("Hospitals", "Hospitals_lyr")


# Add the new field
arcpy.AddField_management("Hospitals_lyr", "FullAdd", "TEXT")

fields = ['NAME', 'ADDRESS', 'CITY', 'ST_ABREV', 'ZIP_CODE', "FullAdd"]

cursor = arcpy.da.UpdateCursor("Hospitals_lyr", fields)

try:
  with cursor as updateCursor:
    for row in updateCursor:
      name = row[0]
      address = row[1]
      city = row[2]
      stateAbb = row[3]
      zipCode = row[4]
      FullAdd = row[5]
      FullAdd = str(name + " " + address + " " + city + ", " \
      stateAbb     + " " + zipCode)
      updateCursor.updateRow(row)


  # Copy feature lyr back to disk
  arcpy.CopyFeatures_management("Hospitals_lyr", "Hospitals_2")
  print "done"

except:
    print "Error"
  • What happens if you remove your try/except statements and run the code that you have presented? – PolyGeo Sep 19 '16 at 21:07
  • 1
    Your try: except: is removing all useful debugging information. This is known as the diaper/nappy pattern of exception handling. You shouldn't do this in general and especially do not do this when posting code questions to GIS-SE as it makes answering your question so much harder. – user2856 Sep 19 '16 at 23:25
  • Thanks for the tip. My apologies. I'm working through a book for a course that I'm taking and it has us use this, but I definitely see the disadvantage of it and I'm going to cease its use. – Alex R Sep 24 '16 at 14:58
3

You need to set row[5] (the new field) to the concatenated value:

with cursor as updateCursor:
    for row in updateCursor:
      name = row[0]
      address = row[1]
      city = row[2]
      stateAbb = row[3]
      zipCode = row[4]
      row[5] = str(name + " " + address + " " + city + ", " \
                   stateAbb + " " + zipCode)
      updateCursor.updateRow(row)

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.