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()
Solved! Go to Solution.
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 + '"'.
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 + '"'.
Thanks for the reply Duncan. Could you provide an example of this?
your best examples of scripts is the online help files
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