Entire field populating with same value

1058
4
Jump to solution
08-08-2014 07:39 AM
NoahHuntington
Occasional Contributor

I am attempting to search directories and sub directories for file in 'name'  and return full file path of found file in a new field.  When I print the value of variable 'string' it prints the desired results However after the script runs the field is populated with a single value instead of unique values for each subsequent row.  Can anyone tell me why this is?

# Set local variable

source = 'R:\\'

fc = "I14__ATTACH_TEST"

field = "ATT_NAME"

addfieldName = "fullPath"

fieldLength = 200

# Add field

arcpy.AddField_management(fc, addfieldName, "TEXT", "", "", fieldLength)

### Attempting to search directories and sub directories for file in 'name'

###    and return full file path of found file (name)

sc = arcpy.SearchCursor(fc)

names = []

for scrow in sc:

    names.append(scrow.getValue(field))

for root, dirnames, filenames in os.walk(source):

        for filename in filenames:

            if filename in names:

                string = os.path.join(root, filename)

                cursor = arcpy.UpdateCursor(fc)

                row = cursor.next()

                while row:

                    # field2 will be equal to field1 multiplied by 3.0

                    row.setValue(addfieldName, string)

                    cursor.updateRow(row)

                    row = cursor.next()

Tags (3)
0 Kudos
1 Solution

Accepted Solutions
DuncanHornby
MVP Notable Contributor

The logic of your cursor loop is flawed. You've created a list of filenames and you enter the if section of your code when it finds a name in names. You then create an update cursor but you have not specified over what, so in this case the cursor defaults to ALL rows in the featureclass. You need to specify a whereclause when you create the cursor, something like field = '"' + filename + '"'.

View solution in original post

0 Kudos
4 Replies
DuncanHornby
MVP Notable Contributor

The logic of your cursor loop is flawed. You've created a list of filenames and you enter the if section of your code when it finds a name in names. You then create an update cursor but you have not specified over what, so in this case the cursor defaults to ALL rows in the featureclass. You need to specify a whereclause when you create the cursor, something like field = '"' + filename + '"'.

0 Kudos
NoahHuntington
Occasional Contributor

Thanks for the reply Duncan. Could you provide an example of this?

0 Kudos
DanPatterson_Retired
MVP Emeritus

your best examples of scripts is the online help files

NoahHuntington
Occasional Contributor

Thanks all for the input! Duncan your reply provided exactly what was needed. Here is what worked for me...

whereClause = """"{}" = '{}'""".format(field, filename)

cursor = arcpy.UpdateCursor(fc, whereClause)

Thanks again,

Noah

0 Kudos