Copy Features - Recieveing Catch All Error Message

713
7
Jump to solution
10-16-2012 10:49 AM
RachelAlbritton1
New Contributor III
I am writing a python code to select features from a feature layer then copying the selected feature(s) to a new feature class. The code succeeds at selecting the features but when it goes to copy these features I get a catch-all error message:

ERROR 000210: Cannot create output CountyBoundary_Selection.shp
Failed to execute (CopyFeatures).
Failed at Tue Oct 16 14:34:23 2012 (Elapsed Time: 0.00 seconds)

I have read this ESRI article, and have made sure that there is not a lock on any files and have tried to save the new feature class to a new location. Any other suggestions?

Also if I use the feature class to feature class tool instead of the Copy Features tool the script works. So I'll go with this for now but it would be nice to know for the future.

import arcpy, os  workspace = "C:/Temp"  print "Workspace set to:", workspace arcpy.AddMessage("Workspace set to: "+workspace)                   arcpy.env.overwriteOutput=True  def whereClause(table, field, values):     """Takes a semicolon-delimited list of values and constructs a SQL WHERE     clause to select those values within a given field and table."""      # Add field delimiters     fieldDelimited = arcpy.AddFieldDelimiters(arcpy.Describe(table).path, field)      # Split multivalue at semicolons and strip quotes     valueList = [value[1:-1]                  if (value.startswith("'") and value.endswith("'"))                  else value for value in values.split(';')]      # Determine field type     fieldType = arcpy.ListFields(table, field)[0].type      # Add single-quotes for string field values     if str(fieldType) == 'String':         valueList = ["'%s'" % value for value in valueList]      # Format WHERE clause in the form of an IN statement     whereClause = "%s IN (%s)"%(fieldDelimited, ', '.join(valueList))     return whereClause  def outName(input,post="Out",fileExtension="shp"):     """Returns output name."""     outName=os.path.basename(input).split(".")[0]+post+"."+fileExtension     return outName   #Make Feature Layer from County Boundary Feature Class InputFC = "C:\Project\ToolData\CountyBoundary.shp" OutputFL = outName(InputFC,"_Layer","lyr")  try:     arcpy.MakeFeatureLayer_management(InputFC, OutputFL) except:     arcpy.GetMessages()      #Select Attributes from County Boundary Layer Field = "CO_NAME" Counties = arcpy.GetParameterAsText(0) SQL = whereClause(OutputFL, Field, Counties)  try:     arcpy.SelectLayerByAttribute_management(OutputFL,"NEW_SELECTION", SQL)     count = int(arcpy.GetCount_management(OutputFL).getOutput(0))     print '\n',"There are", count, "counties selected from County Boundary layer.",'\n'      except:     print arcpy.GetMessages()  #Copy Selected Feature Layer to new Feature Class OutputFC = outName(InputFC,"_Selection","shp")  try:     arcpy.CopyFeatures_management(OutputFL, OutputFC)      except:     print arcpy.GetMessages()
Tags (2)
0 Kudos
1 Solution

Accepted Solutions
T__WayneWhitley
Frequent Contributor
duh, forgive me -  blatant error I didn't see:

set your workspace env variable as such:

arcpy.env.workspace = workspace

(or 1 line):
arcpy.env.workspace = "C:/Temp"

View solution in original post

0 Kudos
7 Replies
T__WayneWhitley
Frequent Contributor
I see your problem - check your variable OutputFL which, as you have it set up by the outName function creates the name:
CountyBoundary_Layer.lyr

...which is really a layer file name - not what the Copy Features tool is expecting.


By the way, if you just want to quickly fix this changing a single line (to get it running without modifying your outName function now), you can make the change:

OutputFL = outName(InputFC,"_Layer","lyr")

...to:

OuputFL = os.path.splitext(outName(InputFC,"_Layer","lyr"))[0]


And that should do it for now --- then you can afford to tweak your function to your liking when time suits you.  (sometimes a luxury hard afforded)  🙂
0 Kudos
RachelAlbritton1
New Contributor III
Wayne - If I'm understanding you correctly you're saying that the input into the Copy Features tool needs to be a .shp file and not a .lyr file correct? If so, this makes me even more confused. The examples shown in ArcGIS 10.0 show that the input can be a layer file, Additionally, the Select by Attributes tool requires that the input (and therefore output) of this process is a lyr file so how can this tool be used to copy an output from this process as shown below?

# Name: ExtactFeaturesByLocationAndAttribute.py
# Description: Extract features to a new feature class based on a spatial relationships to another layer AND an attribute query
# Author: ESRI

# Import system modules
import arcpy

# Set the workspace
env.workspace = "c:/data/mexico.gdb"

# Make a layer from the feature class
arcpy.MakeFeatureLayer_management("cities", "lyr")

# Select all cities which overlap the chihuahua polygon
arcpy.SelectLayerByLocation_management("lyr", "intersect", "chihuahua", 0, "new_selection")

# Within selected features, further select only those cities which have a population > 10,000  
arcpy.SelectLayerByAttribute_management("lyr", "SUBSET_SELECTION", ' "population" > 10000 ')

# Write the selected features to a new featureclass
arcpy.CopyFeatures_management("lyr", "chihuahua_10000plus")
0 Kudos
T__WayneWhitley
Frequent Contributor
Please see my post preceding your last post.... sorry I went on an errand and didn't refresh my screen.
In short, I provided a single line to change for you to test - see if that works for you, then I can explain further if you still need more.

What I was saying is that if you look at the documentation for the Copy Features tool, it is expecting a Feature Layer and this is referenced simply by name (not with the .lyr extension).  It is essentially created 'in memory' - that's why the documentation says such Feature Layers 'disappear' when you exit your ArcGIS session (unless you save outputs to a map as it is auto-added to the TOC, for example)

More to the point, look at this, particularly the output is a Feature Layer, not to be confused with a Layer File:

Make Feature Layer
http://resources.arcgis.com/en/help/main/10.1/index.html#//00170000006p000000

So the output of MFL is to be passed to Copy Features and the output of the 1st tool must match the expected input of the 2nd tool, right?

There are more details, but let's mull that over and stick to what you specifically need for your problem.  Try the modification I gave you - you only need to change a single line to see if it works.  Hope that helps.

I don't think your 1st error code identified the problem, so here's your modified code, with which you may get a 'new' error, but that's part of troubleshooting! (see below):

import arcpy, os

workspace = "C:/Temp" 
print "Workspace set to:", workspace
arcpy.AddMessage("Workspace set to: "+workspace)
                 
arcpy.env.overwriteOutput=True

def whereClause(table, field, values):
    """Takes a semicolon-delimited list of values and constructs a SQL WHERE
    clause to select those values within a given field and table."""

    # Add field delimiters
    fieldDelimited = arcpy.AddFieldDelimiters(arcpy.Describe(table).path, field)

    # Split multivalue at semicolons and strip quotes
    valueList = [value[1:-1]
                 if (value.startswith("'") and value.endswith("'"))
                 else value for value in values.split(';')]

    # Determine field type
    fieldType = arcpy.ListFields(table, field)[0].type

    # Add single-quotes for string field values
    if str(fieldType) == 'String':
        valueList = ["'%s'" % value for value in valueList]

    # Format WHERE clause in the form of an IN statement
    whereClause = "%s IN (%s)"%(fieldDelimited, ', '.join(valueList))
    return whereClause

def outName(input,post="Out",fileExtension="shp"):
    """Returns output name."""
    outName=os.path.basename(input).split(".")[0]+post+"."+fileExtension
    return outName


#Make Feature Layer from County Boundary Feature Class
InputFC = "C:\Project\ToolData\CountyBoundary.shp"

# Try running again - I commented out and replaced your suspect line of code:
#OutputFL = outName(InputFC,"_Layer","lyr")
OuputFL = os.path.splitext(outName(InputFC,"_Layer","lyr"))[0]
 

try:
    arcpy.MakeFeatureLayer_management(InputFC, OutputFL)
except:
    arcpy.GetMessages()
    
#Select Attributes from County Boundary Layer
Field = "CO_NAME"
Counties = arcpy.GetParameterAsText(0)
SQL = whereClause(OutputFL, Field, Counties)

try:
    arcpy.SelectLayerByAttribute_management(OutputFL,"NEW_SELECTION", SQL)
    count = int(arcpy.GetCount_management(OutputFL).getOutput(0))
    print '\n',"There are", count, "counties selected from County Boundary layer.",'\n'
    
except:
    print arcpy.GetMessages()

#Copy Selected Feature Layer to new Feature Class
OutputFC = outName(InputFC,"_Selection","shp")

try:
    arcpy.CopyFeatures_management(OutputFL, OutputFC)
    
except:
    print arcpy.GetMessages()
0 Kudos
RachelAlbritton1
New Contributor III
Thank you for the clarification, that makes sense. I changed the def of outName to omit the file extension type, forcing me to type it in if needed, and went through make the relevant changes in the script, however I still get the same error message. For the output shapefile the current script has the .shp on the end of the file name. i also tried running the script without the .shp (so outName = CountyBoundary_Select), but that didn't work either - same error message. The revised script and error message is below


import arcpy, os

workspace = "C:/Temp" #Change to Set Parameter
print "Workspace set to:", workspace
arcpy.AddMessage("Workspace set to: "+workspace)

arcpy.env.overwriteOutput=True

def whereClause(table, field, values):
    """Takes a semicolon-delimited list of values and constructs a SQL WHERE
    clause to select those values within a given field and table."""

    # Add field delimiters
    fieldDelimited = arcpy.AddFieldDelimiters(arcpy.Describe(table).path, field)

    # Split multivalue at semicolons and strip quotes
    valueList = [value[1:-1]
                 if (value.startswith("'") and value.endswith("'"))
                 else value for value in values.split(';')]

    # Determine field type
    fieldType = arcpy.ListFields(table, field)[0].type

    # Add single-quotes for string field values
    if str(fieldType) == 'String':
        valueList = ["'%s'" % value for value in valueList]

    # Format WHERE clause in the form of an IN statement
    whereClause = "%s IN (%s)"%(fieldDelimited, ', '.join(valueList))
    return whereClause

def outName(input,post="_output"):
    """Returns output name."""
    outName=os.path.basename(input).split(".")[0]+post
    return outName


#Make Feature Layer from County Boundary Feature Class
InputFC = "C:\Project\ToolData\CountyBoundary.shp"
OutputFL = outName(InputFC,"_Layer")

try:
    arcpy.MakeFeatureLayer_management(InputFC, OutputFL)
except:
    arcpy.GetMessages()
    
#Select Attributes from County Boundary Layer
Field = "CO_NAME"
Counties = arcpy.GetParameterAsText(0)
SQL = whereClause(OutputFL, Field, Counties)

try:
    arcpy.SelectLayerByAttribute_management(OutputFL,"NEW_SELECTION", SQL)
    count = int(arcpy.GetCount_management(OutputFL).getOutput(0))
    print '\n',"There are", count, "counties selected from County Boundary layer.",'\n'
    
except:
    print arcpy.GetMessages()

#Copy Selected Feature Layer to new Feature Class
OutputFC = outName(InputFC,"_Selection.shp")

try:
    
    arcpy.CopyFeatures_management(OutputFL,OutputFC)

    print "Selected counties were exported to feature class",'\n'
    
except:
    print arcpy.GetMessages()



ERROR MESSAGE:

Executing: CopyFeatures CountyBoundary_Layer CountyBoundary_Selection.shp # 0 0 0
Start Time: Tue Oct 16 17:01:13 2012
ERROR 000210: Cannot create output CountyBoundary_Selection.shp
Failed to execute (CopyFeatures).
Failed at Tue Oct 16 17:01:13 2012 (Elapsed Time: 0.00 seconds)

OR (removed the .shp from output file)

Executing: CopyFeatures CountyBoundary_Layer CountyBoundary_Selection # 0 0 0
Start Time: Tue Oct 16 17:02:23 2012
ERROR 000210: Cannot create output CountyBoundary_Selection
Failed to execute (CopyFeatures).
Failed at Tue Oct 16 17:02:23 2012 (Elapsed Time: 0.00 seconds)
0 Kudos
RachelAlbritton1
New Contributor III
Wayne - I saw your modified code after replying to you. I tried our code and received the same error message:

Executing: CopyFeatures CountyBoundary_Layer CountyBoundary_Selection.shp # 0 0 0
Start Time: Tue Oct 16 17:05:10 2012
ERROR 000210: Cannot create output CountyBoundary_Selection.shp
Failed to execute (CopyFeatures).
Failed at Tue Oct 16 17:05:10 2012 (Elapsed Time: 0.00 seconds)
0 Kudos
T__WayneWhitley
Frequent Contributor
duh, forgive me -  blatant error I didn't see:

set your workspace env variable as such:

arcpy.env.workspace = workspace

(or 1 line):
arcpy.env.workspace = "C:/Temp"
0 Kudos
RachelAlbritton1
New Contributor III
I can't believe I missed that also, Thanks! That did the trick!
0 Kudos