how to update field with name of FC for list of FCs ?

4632
16
Jump to solution
02-10-2015 02:49 PM
GabrielBacca-Cortes
New Contributor II

Hi Everybody -

I am trying to fill in the attribute in a newly created field 'Particle', with the name of the FC, which will be changing for a list of FCs. I've tried using 'CalculateField', with which I get the error: 'NameError: name 'xy_1' is not defined', where 'xy_1' is the name of the FC going through the loop.

I've tried using 'UpdateCursor' and I get the error: "  'list' object has no attribute 'setValue'  ". 

This is the code I've written so far:

fieldName1 = "Particle"

fieldType1 = "TEXT"

fieldlength = 20

wildcard = ""

fctype = ""

try:

    fcList =  arcpy.ListFeatureClasses(wildcard, fctype)

    # print fcList2

    for fc in fcList:

        print fc

        arcpy.AddField_management(fc,fieldName1,fieldType1,"","",fieldlength,"","NULLABLE")

[with:]

        desc = arcpy.Describe(fc)

        val = desc.name

        print val

        arcpy.CalculateField_management(fc, fieldName1, val, "PYTHON_9.3")

[OR:]

##        curs =  arcpy.da.UpdateCursor(fc,fieldName1)

##        for row in curs:

##            desc = arcpy.Describe(fc)

##            val = desc.name

##            print val

##            row.setValue(fieldName1,val)

##        curs.updateRow(row)

##        del curs, row

0 Kudos
16 Replies
XanderBakker
Esri Esteemed Contributor

You're welcome...

0 Kudos
BlakeTerhune
MVP Regular Contributor

In the line where you open the update cursor, why do you have extra parenthesis around fld_name?

with arcpy.da.UpdateCursor(fc, (fld_name)) as curs:

0 Kudos
TomSellsted
MVP Regular Contributor

Blake,

It must be a tuple.  The extra parenthesis make it a tuple.

Regards,

Tom

0 Kudos
BlakeTerhune
MVP Regular Contributor

But the Esri documentation for the Update cursor says:

For a single field, you can use a string instead of a list of strings.

I'm not trying to be a nit-pick know-it-all, I'm just trying to understand.

0 Kudos
TomSellsted
MVP Regular Contributor

Blake,

You are correct, the docs do say you can use a string for a single field.  In this case just a coding preference.  If you had more fields, the tuple would already be in place.

Regards,

Tom

BlakeTerhune
MVP Regular Contributor

Ah, yes, I follow now. However, I think you have to put an extra comma after the variable inside the parenthesis to make it a true tuple.

fld_name = "Particle"
print fld_name
print (fld_name)
print (fld_name,)

produces:

Particle
Particle
('Particle',)
0 Kudos
GabrielBacca-Cortes
New Contributor II

Blake - yes, it is meant for a list of fields, which in my case is only one.  As it is use in this link ArcGIS Help 10.1 , scroll down to the updateRow function.

Gabriel

0 Kudos