Select to view content in your preferred language

How to get just the filename returned using Calculate Field tool

1743
3
10-09-2012 05:26 AM
StacyVentresca
Emerging Contributor
I'm sure there is a simple answer to this but I'm not seeing it! I want to populate the field I add with just the file name. The code I have below gives me the entire file path populated into the field I add. How can I extract out just the file name?


import arcpy, os, sys, string from arcpy import env from arcpy.sa import*  arcpy.CheckOutExtension("Spatial") arcpy.env.overwriteOutput = True  # Get input parameters for the Zonal Statistics As Table tool inPath = arcpy.GetParameterAsText(0) zoneField = arcpy.GetParameterAsText(1) rasterList = arcpy.GetParameterAsText(2).split(';') outPath = arcpy.GetParameterAsText(3)  for raster in rasterList:         ZonalStatisticsAsTable(inPath, zoneField, raster, outPath)     arcpy.AddField_management(outPath, "RasName", "TEXT")     arcpy.CalculateField_management(outPath, "RasName", '"'+ raster + '"')
Tags (2)
0 Kudos
3 Replies
T__WayneWhitley
Honored Contributor
You've already imported the 'os' python module, so use 'pathname' functions as shown:

The 'basename' function includes the file extension:
os.path.basename(raster)

You can 'nest' functions, e.g., if you want the file name without the ext:
os.path.splitext(os.path.basename(raster))[0]

Returns text (and your variable 'raster' is already text), so you should be able to substitute directly into your expression as:
'"' + os.path.splitext(os.path.basename(raster))[0] + '"'


For documentation see:
http://docs.python.org/library/os.path.html
0 Kudos
StacyVentresca
Emerging Contributor
Thank you very much Wayne! That is exactly what I needed. And thanks for introducing me to the pathname functions.
0 Kudos
T__WayneWhitley
Honored Contributor
My pleasure!  ...I know how it is when looking for a simple fix, know it just must exist, but need a hint  🙂

So, if you don't mind please, would you mark the question answered?  I've just started back participating in these forums, think they're a great resource (I use them too), and you can be my 1st 'correct' or acknowledged-as-useful answer.  Thanks!
0 Kudos