I want to delete all rows in a feature class but remain rows 1 to 5. In other hand I want to remain first five rows and delete others. I know that I have to use search cursor and update cursor but I couldn't use them. How can I delete the rows using ArcPy ?
You can use an Update Cursor to delete rows based on your conditions. In this example, any rows where OBJECTID > 5 is deleted.
import arcpy fc = r'C:\temp\test.gdb\tmp' with arcpy.da.UpdateCursor(fc, "OBJECTID") as cursor: for row in cursor: if row > 5: cursor.deleteRow()
Alternatively, use Select Layer By Attribute (Data Management).
import arcpy, os fc = r'C:\temp\test.gdb\tmp' outws = r'C:\temp\test.gdb' # Make a layer from the feature class arcpy.MakeFeatureLayer_management(fc, "fc_lyr") # Use a SQL query to select OBJECTID 1 - 5 arcpy.SelectLayerByAttribute_management("fc_lyr", "", ' "OBJECTID" <= 5 ') # Write the selected features to a new feature class arcpy.CopyFeatures_management("fc_lyr", os.path.join(outws, "fc_out"))