2

Is there any Python script which will add a field to shapefile which will be corresponding to first three characters from the shapefile name?

2 Answers 2

3

This code should do the trick. New field should be titled "New"

import arcpy
arcpy.env.workspace = r"c:\Temp"
shapename = "newshape.shp"
newfield = shapename[0:3]
arcpy.AddField_management(shapename,newfield,"TEXT","","","20")
3
  • shapename[0:3] would give the first 4 letters, no?
    – Roy
    May 10, 2012 at 16:51
  • 1
    @Roy, This notation starts at and includes the first number, and ends at, but excludes, the last number. May 10, 2012 at 16:54
  • 1
    Thanks, indexing always gets me. Thank god for trial and error.
    – Roy
    May 10, 2012 at 17:54
3

you can do this with Add Field (Data Management).

import arcpy
from arcpy import env

env.workspace = "C:/test.gdb"

inFeat = "cityoflondon.shp"
fieldLength = 10

#it will return "cit" from inFeat
fieldName = str(inFeat[:3])

arcpy.AddField_management(inFeat, fieldName, "TEXT", "", "", fieldLength)
1
  • I forgot to add that i need to add field in multiple shapefiles at once. I have one hundred shapefiles. Sorry, my mistake!
    – com
    May 11, 2012 at 8:08

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.