Initialize fields with values

752
3
09-29-2016 01:23 PM
FrankLaFone
New Contributor

I've got a CSV file with a series of points in each row, point 1, point 2, and point 3.  The row also has a series of attributes that I want to be in the attribute table of the resulting feature class (most notably 'id' and 'token').  I can make the polygons ok, but I'm struggling to figure out how to actually get the values into the fields.  They're all coming up with default values.  I've tried to iterrate back over the resulting shape file to no avail.  I'm not sure what tree to even begin barking up at this point.  Can anyone point me towards what tree to start barking up?

import arcpy

print "Starting!"

fc = 'c:/temp/test.dbf'
#fields = ['Home_y', 'Home_x', 'Work_y', 'Work_x', 'School_y', 'School_x']
fields = ['Home_x', 'Home_y', 'Work_x', 'Work_y', 'School_x', 'School_y', 'id', 'token']

feature_info = []
features = []

with arcpy.da.SearchCursor(fc, fields) as cursor:
   for row in cursor:
      feature = []
      feature = [[row[0],row[1]],[row[2],row[3]],[row[4],row[5]]]
      poly = arcpy.Polygon(arcpy.Array([arcpy.Point(*coords) for coords in feature]),arcpy.SpatialReference(4326))
      arcpy.AddField_management(poly,"id","TEXT")
      arcpy.AddField_management(poly,"token","TEXT")
      #arcpy.CalculateField_management(poly, "id", "Hello_World")
      features.append(poly)

print "Writing shape file..."
arcpy.CopyFeatures_management(features, "c:/temp/polygons.shp")
print "Done writing shape file..."

Tags (1)
Reply
0 Kudos
3 Replies
DanPatterson_Retired
MVP Esteemed Contributor

Not sure what you are looking for... when a field is created, within a FC or shapefile or whatever... a default value is indeed used for the records.  You have no control over this.  This does not differ from when you do it manually.  If you want to ascribe values to the field(s) just created, then you have to calculate a value for it.

FrankLaFone
New Contributor

Ok, but when I calculate a value (which should be just copying a value from the CSV into that field), it says the field doesn't exist.  Yet when I open the shape file, the field is there.

Reply
0 Kudos
DanPatterson_Retired
MVP Esteemed Contributor

You either use an updatecursor to establish values after the field is created or use Calculate Field—Help | ArcGIS for Desktop to establish the values outside an updatecursor, or you create the file from the csv directly.  The field may not 'exist' because the file/field creation has not been completed at the time you are trying to establish a value for it.  It is time sequencing... nothing exists until arcmap says it does

Reply
0 Kudos