I have a script I want to use to update a value for a group of selected features in ArcMap in a string field. I am using the UpdateCursor method but I cannot get the output generated that I want. I know my code is close but something is off. Here is my code:
import arcpy
fc = r'D:\_data\sidewalk.gdb\repairs'
cursor = arcpy.UpdateCursor(fc)
for row in cursor:
if row.FixedBy == '':
row.FixedBy = 'Contractor'
cursor.updateRow(row)
print "Processing complete"
del row
I am trying to update the string "FixedBy" field where values are blank, not 'Null', with the value 'Contractor'. What is my code missing?
2 Answers 2
This should work if the value of FixedBy is NULL or blank (meaning no text at all, including spaces):
import arcpy
fc = r'D:\_data\sidewalk.gdb\repairs'
with arcpy.da.UpdateCursor(fc,['FixedBy']) as cursor:
for row in cursor:
if row[0] == None or row[0] == '':
row[0] = 'Contractor'
cursor.updateRow(row)
-
This runs perfectly thank you! If the GDB is stored on an SDE server what would the file path look like?cbunn– cbunn2017年06月15日 21:04:54 +00:00Commented Jun 15, 2017 at 21:04
-
Glad it helped. You could look at this answer to know how to do that. gis.stackexchange.com/a/5541/9518.umbe1987– umbe19872017年06月16日 11:01:53 +00:00Commented Jun 16, 2017 at 11:01
One idea is to pass in a where clause to the UpdateCursor; then you don't need to check any values. All rows returned could be updated.
Assuming you are using 10.1+, switching to arcpy.da cursors is also recommended.
import arcpy
fc = r'D:\_data\sidewalk.gdb\repairs'
i = 0
with arcpy.da.UpdateCursor(fc, ['FixedBy'], "FixedBy =''") as cursor:
for row in cursor:
row[0] = 'Contractor'
cursor.updateRow(row)
i += 1
print "Processed {}...".format(i)
(Untested code.)
If the count is 0, there is a problem with your where clause or your data isn't what you think you are seeing.
-
OP mentioned in the comments that other edits were also being made in the cursor loop, so the where clause may not be appropriate in this specific case.Bjorn– Bjorn2017年06月08日 21:00:36 +00:00Commented Jun 8, 2017 at 21:00
-
It says it processed all the records despite me only selecting 2 records for it to run against. Also it did not update the "FixedBy" field. It is a string field in a File GDB. How do I adjust my where clause?cbunn– cbunn2017年06月08日 21:18:49 +00:00Commented Jun 8, 2017 at 21:18
-
@cbunn Try
"\"FixedBy\" = ''"
as your where clauseBjorn– Bjorn2017年06月08日 22:47:17 +00:00Commented Jun 8, 2017 at 22:47
cursor.updateRow(row)
should be unindented. Try replacingrow.FixedBy == ''
withrow.FixedBy == None
. Also, I would recommend using the new data accessda
cursors.print
statement within your cursor to see what the true value is of yourrow
.