[GIS] How to use for loop to add and calculate new field

arcgis-10.2arcgis-desktoparcpypython

I am trying to use for loop to add and calculate a newfield for 2 shapefiles and a different new field for 2 other shapefiles. When I tried to do these 2 loops as one, it did not work so I separated them into 2 loops and it worked. I am using python 2.7 stand alone (arcmap 10.2).

more details: So I want to make a new field and add 'CA' to shapefiles containing _CA.shp (*_CA.shp). I also want to make a new field and add 'AZ' to shapefiles containing _AZ.shp (*_CA.shp). When I created a loop (the first code), I got my roads_CA and railroads_CA to work but roads_AZ and railroads_AZ did not create a new field containing 'AZ'. I did not get an error which means the loop ran through but I guess the elif came out false so it did not create anything.

here is my code:

    CAshp = arcpy.ListFiles("*_CA.shp")

    for CA in CAshp:
        if (CAshp == 'roads_CA.shp', CAshp == 'railroads_CA.shp'):
        newField = 'StateAbbre'
        arcpy.AddField_management(CA, newField, 'TEXT')
        arcpy.CalculateField_management(CA, newField, "'CA'", "PYTHON_9.3")
    elif (CAshp != 'roads_AZ.shp', CAshp != 'railroads_AZ.shp'):
        AZshp = CAshp.extend(arcpy.ListFiles("*_AZ.shp"))
        newField = 'StateAbbre'
        arcpy.AddField_management(AZshp, newField, 'TEXT')
        arcpy.CalculateField_management(AZshp, newField, "'AZ'", "PYTHON_9.3") 

Best Answer

Try extending the list of files; the elif isn't finding any AZ's since [CAshp] only has CA's from "*CA.shp".

CAshp = arcpy.ListFiles("*_CA.shp")
CAshp.extend(arcpy.ListFiles("*_AZ.shp")
for CA in CAshp: 
    if CA == 'roads_CA.shp' or CA == 'railroads_CA.shp':
        arcpy.AddField_management(CA, 'StateAbbre', 'TEXT')
        arcpy.CalculateField_management(CA, newField, "'CA'", "PYTHON_9.3")
    elif CA == 'roads_AZ.shp' or CA == 'railroads_AZ.shp':
        arcpy.AddField_management(CA, 'StateAbbre', 'TEXT')
        arcpy.CalculateField_management(AZshp, newField, "'AZ'", "PYTHON_9.3")

for clarity, maybe I should have renamed the varibles:

# add CA's and then extend list with AZ's
shapes = arcpy.ListFiles("*_CA.shp")
shapes.extend(arcpy.ListFiles("*_AZ.shp")
for shp in shapes: 
    # first part of the loop for CA's
    if shp == 'roads_CA.shp' or shp == 'railroads_CA.shp':
        arcpy.AddField_management(shp, 'StateAbbre', 'TEXT')
        arcpy.CalculateField_management(shp, newField, "'CA'", "PYTHON_9.3")
    # second part of the loop for AZ's
    elif shp == 'roads_AZ.shp' or shp == 'railroads_AZ.shp':
        arcpy.AddField_management(shp, 'StateAbbre', 'TEXT')
        arcpy.CalculateField_management(shp, newField, "'AZ'", "PYTHON_9.3")
Related Question