Select by attributes and delete selected records with arcpy

Question:

Got 11 Tables exported to gdb from excel files.

Those Tables have the same structure (same fields) but different data.

Records from the Tables contain useless data which needs to be deleted in the script process.

In ArcGIS Pro I delete that useless data with the Select by Attributes tool:

Select [Where] [FieldName] [contains the text] [uselesstext]

And then delete the selected records.

But I need to put this process into the script though can not find the proper code or hint to create the function.

Updated code:

import arcpy
import re
fc = r'D:YourFolderNameYourGDBName.gdbYourFeatureClassName'

with arcpy.da.UpdateCursor(fc, "YourFieldName") as cursor:
    for row in cursor:
        if re.match(r"YourWordHere.+", row[0]):
            cursor.deleteRow()

This code works when searched word stands at start of the field.

import arcpy
import re
fc = r'D:YourFolderNameYourGDBName.gdbYourFeatureClassName

with arcpy.da.UpdateCursor(fc, "YourFieldName", where_clause="YourFieldName LIKE '%YourWordHere%'") as cursor:
    for row in cursor:
        cursor.deleteRow()

This code works with a word at any part of the field.

Asked By: ZaZa M.

||

Answers:

if row[0] is LIKE regist% is not a valid python code, you can’t use SQL syntax directly like this. Instead, try to rephrase the condition with python syntax. For example:

import re

with arcpy.da.UpdateCursor(fc, "owner") as cursor:
    for row in cursor:
        if re.match(r"regist.+", row[0]):
            cursor.deleteRow()

Another option is to put the SQL-like condition in the UpdateCursor itself:

with arcpy.da.UpdateCursor(fc, "owner", where_clause="owner LIKE 'regist%'") as cursor:
    for row in cursor:
        cursor.deleteRow()
Answered By: isshp
Categories: questions Tags: , ,
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.