1

I have a set of shapefiles that need a new field adding to them called "Policy_Ref". I then need to update this field with the shapefile name. However when I do, it uses the full title, including the .shp. However I do not want the .shp in the fields. This is my code so far:

import arcpy
arcpy.workspace.env = r"teamGIS/shp"
fcs = arcpy.ListFeatureClasses()
for fc in fcs:
    arcpy.AddField_management(fc, "Policy_Ref", "TEXT")
    arcpy.CalculateField_management(fc, "Policy_Ref", "'" + fc + "'")
    arcpy.Merge_management(fcs, "new_shp")

How do I remove the .shp either before or after the code is executed?

2

This is really a Python rather than ArcPy question, so would be best researched at Stack Overflow.

However, you can try changing:

arcpy.CalculateField_management(fc, "Policy_Ref", "'" + fc + "'")

to:

arcpy.CalculateField_management(fc, "Policy_Ref", "'" + fc.replace(".shp","") + "'")
  • 1
    my personal favorite is fcName,fcExt = os.path.splitext(fc).. this way if there is no extension fcExt == '' but fcName always contains the name; this function also has tolerance for double extensions (eg. MyShp.tif.shp). – Michael Stimson Jun 26 '15 at 3:39
3

Or you could use a describe and .baseName

    fcs = arcpy.ListFeatureClasses("","","")
    for fc in fcs:
            desc = arcpy.Describe(fc)
            print fc
            print desc.baseName
            ActualName = desc.baseName

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.