add and calculate field

531
3
Jump to solution
09-29-2011 03:40 PM
YinghaiKe
New Contributor
I want to add a field "filename" with "TEXT" format for a shape file and assign this field with the file name. The shape file only has one record. Here is my code:

import arcpy
from arcpy import env

# Set environment settings
env.workspace = "D:/Workspace"

fc = "01055p.shp"
tmp = fcname.split('.')
tmp2 = tmp[0]

arcpy.AddField_management(fc, "filename", "TEXT", "", "", 25)
arcpy.CalculateField_management(fc, "filename", tmp2)

But I got error saying "CalculateField_management" failed to execute. Is there any problem with the script? Thanks!
Tags (2)
0 Kudos
1 Solution

Accepted Solutions
MarcNakleh
New Contributor III
Hello,

If you're creating the textfield filename, and trying to write text to it, I think I see the problem.
For string literals, your expression value needs to be encapsulated by quotes when it's passed to the Field Calculator. Your code should therefore be:
arcpy.CalculateField_management(fc, "filename", '"' + tmp2 + '"')


What you were passing to the expression field before was this:
myfilename

whereas what you wanted to send, and what you'd see in the Field Calculator, is this:
"myfilename"


Hope this helps!

View solution in original post

0 Kudos
3 Replies
StacyRendall1
Occasional Contributor III
What is fcname? You don't specify it before calling it. Although, that isn't directly related to your error.

You could try adding:
arcpy.AddMessage('%s' % tmp2)

just before your add field line, to check what tmp2 is actually coming out like before the calculation.
0 Kudos
MarcNakleh
New Contributor III
Hello,

If you're creating the textfield filename, and trying to write text to it, I think I see the problem.
For string literals, your expression value needs to be encapsulated by quotes when it's passed to the Field Calculator. Your code should therefore be:
arcpy.CalculateField_management(fc, "filename", '"' + tmp2 + '"')


What you were passing to the expression field before was this:
myfilename

whereas what you wanted to send, and what you'd see in the Field Calculator, is this:
"myfilename"


Hope this helps!
0 Kudos
YinghaiKe
New Contributor
Thank you, mnakleh, that works great! Thanks!
0 Kudos