Select to view content in your preferred language

Select first row of feature class and export to shapefile using SearchCursor

1795
2
06-11-2010 12:05 AM
KevinCressy
New Contributor II
I am trying to test a portion of code for a script I am trying to put together.  I would like to go the the first row in my shapefile using the SearchCursor and then export that row to new shapefile (eventually I want to develop this to export each row - however the first row on its own is fine for now).  I have tried the following script but this does not work, can anyone tell me where I am going wrong?

import arcgisscripting

gp = arcgisscripting.create(9.3)
gp.overwriteOutput = 1

inpolys = r'C:\Python_Test\Polygons.shp'

infc = inpolys

rows = gp.SearchCursor(infc)

row = rows.next() # take me to first row in polygon file

# Make a temp layer
gp.MakeFeatureLayer("C:\Python_Test\Polygons.shp", "TempLayer")
# Copy row features out
gp.CopyFeatures("TempLayer", "C:\Python_Test\Test.shp")
0 Kudos
2 Replies
DanPatterson_Retired
Deactivated User
http://arcscripts.esri.com/details.asp?dbid=14127
will do it if you select a unique ID field for the export (ie FID)
0 Kudos
JeffWard
Regular Contributor II
Here is what I came up with.  This code loops through all of the features and inserts them to the new shapefile.  If you run it multiple times, it will stack the new features on top of the old ones.

import arcgisscripting

gp = arcgisscripting.create(9.3)

gp.overwriteoutput = 1
# set the workspace
gp.workspace = "C:\\Python_Test"

inPolys = "Polygons.shp"

#need the spatial reference for the CreateFeatureClass tool below
dscFC = gp.Describe(inPolys)
sr = dscFC.SpatialReference

newFC = "NewFeatures.shp"
#if the new shapefile doesn't exist it will be created
if not gp.Exists(newFC):
    gp.CreateFeatureClass_management(gp.workspace, newFC, "POLYGON", inPolys, "", "", sr)

oldRows = gp.SearchCursor(inPolys)
newRows = gp.InsertCursor(newFC)
oldRow = oldRows.Next()
while oldRow:
    #if you need to do anything to the features before they are inserted
    #into the new shapefile, this is where you would do it.
    newRows.InsertRow(oldRow)
    oldRow = oldRows.Next()

del gp, dscFC, sr, oldRows, newRows, oldRow


I hope that helps you out.

Jeff Ward
Jeff Ward
Summit County, Utah
0 Kudos