SearchCursor - RuntimeError: cannot open - Feature Class

10870
6
07-23-2017 06:26 PM
BWSCIM
by
New Contributor III

I'm attempting to read a specific field from a Feature Class using the following code (search cursor):

import arcpy
import os

arcpy.env.workspace = 'C:\Users\jas\Documents\ArcGIS\L_Sr_geodatabase.gdb'

#inputFeatures = arcpy.GetParameterAsText(0)
inFeatures = 'LF_Stormdrains'

fc = os.path.join(arcpy.env.workspace,inFeatures)

# check if exist
if arcpy.Exists(fc):
   print "Feature Class Exists"

# check name
fc_list = arcpy.ListFeatureClasses()    

for fcname in fc_list:  
    arcpy.AddMessage(fcname) 


fields = ['ASSET_ID']

if arcpy.Exists(inFeatures):
     arcpy.AddMessage("Feature Class Exists...")

with arcpy.da.SearchCursor(fc, fields) as cursor:
     try:
          if cursor.next() != ():
               cursor.reset()
               for row in cursor:
                    assetID = row[0]
                    arcpy.AddMessage(assetID)
     except StopIteration:
          print('Empty Cursor')

I'm stumped on the RuntimeError: cannot open 'feature class'.  Any help would be appreciated!

0 Kudos
6 Replies
MitchHolley1
MVP Regular Contributor

What exactly are you trying to accomplish with the Search Cursor?

Don't forget to add an 'r' in front of your database path. 

#No :(
arcpy.env.workspace = 'C:\Users\jas\Documents\ArcGIS\L_Sr_geodatabase.gdb'

#Yes :)
arcpy.env.workspace = r'C:\Users\jas\Documents\ArcGIS\L_Sr_geodatabase.gdb'
0 Kudos
BWSCIM
by
New Contributor III

Thanks Mitch, I'll try this. Ultimately I'm trying to do some relational queries between feature classes based on an Asset_ID.

Additionally, Ive noticed that as I change feature classes it will run the first time, then provide the same runtime error when I try and run the script again.  Am I not releasing the cursor properly?

0 Kudos
MitchHolley1
MVP Regular Contributor

Yeah, I've never seen a cursor like that before.  Please check this link on SearchCursor.  You don't necessarily have to set an arcpy.env.workspace either. 

It should look similar to this: 

database = r'C:\pathtoDatabase.gdb'
fc = database + '/' + 'fc'

fields = ['AssetID']

with arcpy.da.SearchCursor(fc, fields) as cursor:
    for row in cursor:
        assetID = str(row[0])
        arcpy.AddMessage(assedID)
del cursor

‍‍‍‍‍‍‍‍‍
0 Kudos
AlexanderBrown5
Occasional Contributor II

Mitch gives a great example above -- it is really important to close your cursor:

del cursor
‍

If you do not, then you will have a persistent lock on the data.  

0 Kudos
RichardDaniels
Occasional Contributor III

Nice of ESRI included this gem in their examples 🙂

0 Kudos
BruceHarold
Esri Regular Contributor

Hi, on the off chance your 'relational queries' involve set comparison this might be useful:

https://pm.maps.arcgis.com/home/item.html?id=e638afe0695a4ad38388cb8d9b350446 

0 Kudos