I am trying to create a code that will accept the input of a shapefile, and separate each of its features into separate shapefiles into a specified directory location. Can anyone help ? I am trying to use pyshp module, but it is only able to delete one file.
Asked
Active
Viewed 1,640 times
2 Answers
4
I'm not sure solutions to this problem have anything to do with deleting files, so pyshp probably works fine. Here's how to split a Natural Earth shapefile feature-by-feature with Fiona:
import os
import fiona
dest = "/tmp/countries/"
infile = (
"/Users/seang/data/ne_50m_admin_0_countries/"
"ne_50m_admin_0_countries.shp")
with fiona.open(infile) as source:
meta = source.meta
for f in source:
outfile = os.path.join(dest, "%s.shp" % f['id'])
with fiona.open(outfile, 'w', **meta) as sink:
sink.write(f)
sgillies
- 9,056
- 1
- 33
- 41
0
I am not familiar with python, but I have designed an implementation for you in ArcObjects. This code will loop through all features in a specified shapefile for you, where inputshpFilePath is the full filepath for your input shapefile.
ESRI.ArcGIS.Geodatabase.IWorkspaceFactory pWSFact; //create general workspace factory (this is the directory you will be working in)
pWSFact = new ShapefileWorkspaceFactory(); //set general workspace as a shapefile workspace
ESRI.ArcGIS.Geodatabase.IFeatureWorkspace pFeatureWorkspace; //create a feature workspace to handle features
pFeatureWorkspace = (IFeatureWorkspace)pWSFact.OpenFromFile(inputshpFilepath, 0); //set feature workspace as the shapefile workspace defined earlier, and specify a file location
ESRI.ArcGIS.Geodatabase.IFeatureCursor pFCursor1; //use to loop through the feature class. You can think of this as a marker that grabs each feature as it loops through the array of features
pFCursor1 = pFeatureLayer.Search(null, false);
long recNum; //store the position you are at in the array. This is the array counter
recNum = pFeatureLayer.FeatureClass.FeatureCount(null); //set our counter at 0
ESRI.ArcGIS.Geodatabase.IFeature pFeature1; //declare an instance of ifeature to store the feature itself
pFeature1 = pFCursor1.NextFeature(); //get the feature from the marker as it loops through the array
while (!(pFCursor1 == null))
{
//YOUR CODE TO SPLIT EACH FEATURE AND SAVE IT INTO A DIRECTORY LOCATION
//WILL GO HERE. YOU WILL HAVE TO CREATE A SHAPEFILE PROGRAMMATICALLY FOR
//EACH FEATURE AND
//THEN COPY OVER THE SELECTED FEATURE INTO THE NEW EMPTY SHAPEFILE
pFCursor1.NextFeature(); //step to next feature in the array. This will continue until all features have been selected.
}
Hope this helps. Even if you aren't able to implement an ArcObjects solution you may be able to translate some of this logic over to Python.
Conor
- 3,032
- 2
- 16
- 44