Select to view content in your preferred language

Python Script: Create separate feature classes for each record in shapefile

3955
12
05-28-2019 06:12 AM
MarkNorris-Rogers
Emerging Contributor

Dear Forum Members,

I need to create a separate feature class from each record in a shapefile
(i.e. each row in original shapefile needs to be a new feature class in its own right).
I need to name each new feature class by its ID number from the AWS_ID field in the original shapefile
See Python script below:

1.#Import required modules
2.import arcpy, os, traceback
3.from arcpy import env
4.
5.env.workspace = r"C:\temp\"
6.env. overwriteOutput = True
7.
8.# Script arguments
9.awsInput = r"C:\Temp\AWS.shp"
10.awsName = "AWS_ID" # Field in AWS.shp to be used as name for output shpfile
11.cursor = arcpy.SearchCursor(awsInput)
12.
13.for aws in cursor:
14. awsID = aws.getValue(awsName)
15. awsName = "{}_AWS".format(aws)
16. arcpy.CopyFeatures_management(awsInput, r"C:\Temp\DataExtract_Work.gdb\awsName", "0", "0", "0")

(NB. line numbers will affect indentation!)

I have tried to get it working by
a) searching the arcpy help - source of line 11, SearchCursor
b) reviewing Esri online Python courses I have done - source of line 15
c) viewing online video tutorials on ModelBuilder iteration

Before I added lines 14,15 but ran line 16,the script ran but either overwrote all but the last record or
added all the records as per the original shapefile. Currently I get a RuntimeError: ERROR 999999,
referring to line 14. Prior to adding lines 15-16, and having a print aws.getValue(aws) statement,
it printed out each ID number on a separate line.

Question 1. Where have I messed up?

Question 2. Does one have to first create a list if one is only using a single feature class/shapefile as the input?

Any help will be appreciated.

Kind regards,
Mark

0 Kudos
12 Replies
DuncanHornby
MVP Notable Contributor

I agree with Neil Ayres‌ to explode out your data into individual shapefiles does seem a little "excessive". Going down that road incurs all sorts of file management issues where a single cursor feeding out your point for the raster processing would be much more sensible and efficient, unless its an issues with some sort of mega dataset as Luke suggested? I would be going back to the client and challenging them to understand why they really need it in that format and see if they could not adapt/improve their workflow.

If turns out they are using ArcView 3.2 on a windows XP machine with 8MB of ram then fair enough...

JoeBorgione
MVP Emeritus

If turns out they are using ArcView 3.2 on a windows XP machine with 8MB of ram then fair enough...

This wouldn't be so funny if it weren't so true...

That should just about do it....
NeilAyres
MVP Alum

I have seen many projects in the past which contain thousands of shapefiles, which actually should be consolidated into one feature with an attribute indicating what is what.