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 Answers 2
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
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","") + "'")
-
1my 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– Michael Stimson2015年06月26日 03:39:04 +00:00Commented Jun 26, 2015 at 3:39