0

I have four folders, each with 50 sub folders. Within each sub folder I have 80 shapefiles. For the first shapefile within each sub folder I want to add a field and populate that field with the name of the sub folder.

I am attempting to do this like so:

import arcpy
import os

folders=r'F:\Sheyenne\grazing_final\pressure_per_pixel_by_allotment\allotment_points' #path to four folders
for folder in os.listdir(folders):


    for sub in os.listdir(os.path.join(folders,folder)): #path to sub folders

        arcpy.env.workspace=os.path.join(folders,folder,sub)  #set environment
        shapefiles=[os.path.join(arcpy.env.workspace, i) for i in arcpy.ListFeatureClasses('*.shp')]
        shapefiles=shapefiles[0] #return only the first shapefile from each sub folder

        arcpy.AddField_management(shapefiles, "Allotment", "SHORT", "5") #add new field to each shapefile

        with arcpy.da.UpdateCursor(shapefiles, 'Allotment') as cursor: #populate each field with the string contained in sub
        for row in cursor:
            row.setValue(sub)
            cursor.updateRow(row)
        del row  

but this returns:

 File "F:/python codes/prelim_codes/grazing_regression.py", line 78, in <module>
    row.setValue(allotment)

AttributeError: 'list' object has no attribute 'setValue'
1
  • You don't have 78 lines in your code snippet, yet your error refers to line 78, and a line of code that I can't see in your snippet. Have you tested your snippet as posted above, and what error do you get from that?
    – Midavalo
    Oct 21, 2016 at 20:07

1 Answer 1

2

First your indent is wrong in your with - the for line should be indented further (and also the lines contained within the for). Also you don't need to del row if it's contained within the with block.

You appear to be mixing code from two types of Update Cursors. With the arcpy.da.UpdateCursor() your row is returned as a list of fields values which you can update using row[0] = x etc.

with arcpy.da.UpdateCursor(shapefiles, 'Allotment') as cursor: #populate each field with the string contained in sub
    for row in cursor:
        row[0] = sub
        cursor.updateRow(row)

So in the code here each record has the value of sub written to the Allotment field. It will be the same value written to every record in your shapefile.

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.