top of page

Adding a Text Field

The Python script adds a text field to the roads.shp feature class called FERRY and populates this field with YES and NO values, depending on the value of the FEATURE field.

# Ehsan Momeni

from arcpy import env, da, AddFieldDelimiters, Buffer_analysis, DeleteFeatures_management, ValidateFieldName, \
     ListFields, Select_analysis, AddField_management

env.workspace = r"C:\Users\emomeni\"  # workspace
env.overwriteOutput = True   # overwriting outputs

fc = "roads.shp"  # input feature class


newfield = "FERRY"  # new field to be created
fieldtype = "TEXT"  # type of the filed that is going to be created
fieldname = ValidateFieldName(newfield)  # to determine whether a specific name is valid or not
fieldlist = ListFields(fc)  # all fields in the input feature class
fieldnames = []

# trying to see if the field is already exist of not. if not, creates it
for field in fieldlist:
    fieldnames.append(field.name)
if fieldname not in fieldnames:
    AddField_management(fc, fieldname, fieldtype, "", "", 3)  # Creating a new field
    print ("%s filed has been added." % newfield)
else:
    print ("%s field name already exists." % newfield)

# to search in the first field and update other field
fields = ['FEATURE', newfield]  # first one is the filed we apply condition, the other is the filed we wanna update it
with da.UpdateCursor(fc, fields) as cursor:
    for row in cursor:
        if row[0] == "Ferry Crossing":
            row[1] = "YES"
        else:
            row[1] = "NO"
        cursor.updateRow(row)
print ("%s field has been updated." % newfield)


        else:
            row[1] = "NO"
        cursor.updateRow(row)
print ("%s field has been updated." % newfield)

google_scholar1-300x150.png
ResearchGate.png
Ehsan Momeni ORCID GIS Remote Sensing Ur
Ehsan Momeni LinkedIn GIS Remote Sensing
ncbi-300x150.png
academia.png

(Information on this website may not be up to date)

bottom of page