TransWikia.com

Splicing a string and adding a charcter with update cursors issue

Geographic Information Systems Asked by JB19 on March 3, 2021

I am new to python, so I am trying to figure these things out on the fly so please bare with me if this is an easy task. I am using the name of my Feature Classes to populate an attribute field with update cursors, but I am trying to add a dash 2 spaces from the left. For example the feature class is name OB619 and I need to populate the ID field as OB-619. I was able to get the update cursor to take the name of the Feature Class, but I haven’t been able to figure outnhow to use splicing in the cursor to add the dash. Any help would be greatly appreciated.

arcpy.env.workspace = r'PublicOB_Test_3.gdbTest1'

def makeFullPath(path, name):
    return path + "" + name


file_name_field = "ID"
fieldname2 = "FLOATABLES"
fieldname3 = "PATHOGENS"
fieldname4 = "NITROGEN"
fieldname5 = "OWNERSHIP"



feature_classes = arcpy.ListFeatureClasses()

fieldsList = [file_name_field, fieldname2, fieldname3, fieldname4, fieldname5 ]

for fc in feature_classes:
    existing_fields = [f.name for f in arcpy.ListFields(fc)]
    if fieldsList not in existing_fields:
       arcpy.management.AddField(fc, file_name_field, 'TEXT', field_length=200)
       arcpy.management.AddField(fc, fieldname2, 'TEXT', field_length=50)
       arcpy.management.AddField(fc, fieldname3, 'TEXT', field_length=50)
       arcpy.management.AddField(fc, fieldname4, 'TEXT', field_length=50)
       arcpy.management.AddField(fc, fieldname5, 'TEXT', field_length=50)
       # write the file name into each row of the file name filed

    with arcpy.da.UpdateCursor(fc, [file_name_field]) as uc:
        for row in uc:
            uc.updateRow([str(fc)])
    del row, uc

One Answer

To add a dash 2 spaces from the left you can do:

fc= fc[:-2] + "-" + fc[-2:]

Based on your question and example I'm not sure exactly what your goal is, but I think you would want to replace the cursor with the following to get your desired output:

with arcpy.da.UpdateCursor(fc, [file_name_field]) as uc:
        for row in uc:
            row[1] = fc[:-2] + "-" + fc[-2:]
            cursor.updateRow(row) 

Answered by Pdavis327 on March 3, 2021

Add your own answers!

Ask a Question

Get help from others!

© 2024 TransWikia.com. All rights reserved. Sites we Love: PCI Database, UKBizDB, Menu Kuliner, Sharing RPP