1

I have a small script that should take the name of the file and add it to a newly created field in several shapefiles.

import arcpy

arcpy.env.workspace = r"c:\users\athom\desktop\timber\New4"

arcpy.env.overwriteOutput = True

fcs = arcpy.ListFeatureClasses()

for fc in fcs:
    field = 'NAME'
    expression = str(fc)
    print expression
    arcpy.AddField_management(fc, field, "TEXT")
    arcpy.CalculateField_management(fc, field, "expression", "PYTHON")

del expression
del fc
del fcs

However, the file name of the first feature is written into the attribute table for each following features even though it shows in the python interpreter as the correct file name as "expression" - the attribute for NAME ends up being SA14107.shp in each shapefile.

python output

Why is the expression not being overwritten?

3

You need to pass the expression as a quoted string, like this:

arcpy.CalculateField_management(fc, field, "'" + expression + "'" , "PYTHON")

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.