I have a python script that I use to make batch updates on a database in GIS.
I'm using Update Cursors to update the values of an attribute table, which has worked flawlessly when I am updating records for the first time since UpdateCurosrs overwrite the data (from what I understand as a still-newish coder).
When I revisit a record and need to add (or append) comments to a populated record, I can do so in two different chunks of code, but its clunky and requires additional steps. I'm trying to combine these two pieces of code into a single script with a nested if/else loop.
To overwrite blank attributes, this code works perfectly
fc=DB
fieldname=["StationID","StationStatus","StatusComments_Source"]
for i in confirm:
with arcpy.da.UpdateCursor(fc,fieldname) as cursor:
for row in cursor:
if (row[0]== i):
row[1]= "Confirm" #Data Confirmed
row[2]= StatusComments_Source #Comments
cursor.updateRow(row)
If I want to append comments to existing fields, this code works perfectly. This code will break if that attribute field for row2 is empty.
for i in confirm:
with arcpy.da.UpdateCursor(fc,fieldname) as cursor:
for row in cursor:
if (row[0]== i):
row[1]= "Confirm" #Data Confirmed
confcom=[]
confcom.append(StatusComments_Source)
row[2]=''.join(confcom)
cursor.updateRow(row)
This is the loop I tried to create, "If row2 is null, overwrite the data, else: append the comments
for i in confirm:
with arcpy.da.UpdateCursor(fc,fieldname) as cursor:
for row in cursor:
if (row[0]== i):
row[1]= "Confirm" #Data Confirmed
if row[2] is None:
row[2] = StatusComments_Source
else:
confcom=[]
confcom.append(row[2],", ")
confcom.append(StatusComments_Source)
row[2]=''.join(confcom)
cursor.updateRow(row)
But I get this error:
Traceback (most recent call last):
File "C:\Users\CEI2\AppData\Local\Temp\ipykernel_19768\350652596.py", line 13, in <cell line: 4>
confcom.append(row[2],", ")
TypeError: list.append() takes exactly one argument (2 given)
I'd appreciate any help with this!!
If you have an existing comma-separated field, and you want to add another item to it, use split()
to separate it into a list, append to that list, join it back to a string and assign that back to the field.
if row[2] is None:
row[2] = StatusComments_Source
else:
confcom=row[2].split(', ')
confcom.append(StatusComments_Source)
row[2]=', '.join(confcom)
You can also just use string concatenation:
row[2] += f', {StatusComments_Source}'