AnsweredAssumed Answered

Field calculation in Python - expression not defined

Question asked by mpgresham99 on Oct 1, 2013
Latest reply on Oct 16, 2013 by mpgresham99
Hi,

Apologies if something similar has been asked before in a previous post. I'm trying to add a field and then calculate it with the name of the file. The python script I'm trying to run below seems to run okay however it falls over at the calculate field step of the process.

import os, arcpy

Input = "C:\\GIS\\TempFile.shp"
expression = os.path.basename(Input).rstrip(os.path.splitext(Input)[1])
print Input
print expression

# Add field called "Filename"
arcpy.AddField_management("TempFile","Filename","TEXT",254)

# Calculate field with file name
arcpy.CalculateField_management(Input, "Filename", expression, "PYTHON")


The error that comes up is:

ERROR 000539: Error running expression: expression
Traceback (most recent call last):
  File "<expression>", line 1, in <module>
NameError: name 'expression' is not defined

However I find this confusing as I would've thought the line below defines "expression".

expression = os.path.basename(Input).rstrip(os.path.splitext(Input)[1])

I feel I'm pretty close to getting it however I need a helping hand from somewhere. Any feedback would be welcomed.

Regards,
Mike

Outcomes