Select to view content in your preferred language

Error using SearchCursor to export values to text file

3147
18
06-13-2014 08:58 AM
EstherOlson-Murphy
New Contributor
I have created a very basic script (with the help of others) that uses a searchCursor to pull data from a feature class and, in theory, add that data to a text file.
I think I almost have it but I am still getting a few errors that I cannot figure out (I am completely new to python and am at a complete loss now).

The first error I get is as follows:
Traceback (most recent call last):
File "G:\Olson-Murphy_Week10\Scripts\MaterialSearch2.py", line 10, in <module>
Qry = "Material = " + '%s' %materialType
NameError: name 'materialType' is not defined

Failed to execute (MaterialReport).

By removing "%materialType" from the script i get this error to go away but then I am faced with another:

Traceback (most recent call last):
File "G:\Olson-Murphy_Week10\Scripts\MaterialSearch2.py", line 14, in <module>
MaterialSearch = arcpy.SearchCursor(fc,Qry, fields = "Material;Diameter;System")
File "c:\program files\arcgis\desktop10.1\arcpy\arcpy\__init__.py", line 1133, in SearchCursor
return gp.searchCursor(dataset, where_clause, spatial_reference, fields, sort_fields)
File "c:\program files\arcgis\desktop10.1\arcpy\arcpy\geoprocessing\_base.py", line 359, in searchCursor
self._gp.SearchCursor(*gp_fixargs(args, True)))
RuntimeError: ERROR 999999: Error executing function.

Failed to execute (MaterialReport).

My code can be found below. Anyone have any suggestions? (this code someone else did say worked on their machine so I am at a total loss)

import arcpy
# Set workspace
arcpy.env.workspace = r"G:\Olson-Murphy_Week10\SouthFloridaNaturalGas.gdb"


#Estabslish input feature class
fc = r"G:\Olson-Murphy_Week10\SouthFloridaNaturalGas.gdb\Mains"

# Establish materials search for tool
Qry = "Material = " + '%s' %materialType


# Create cursor to search gas mains by material
MaterialSearch = arcpy.SearchCursor(fc,Qry, fields = "Material;Diameter;System")

#Define output
outReport = arcpy.GetParameterAsText(1)

#Open the report text file in write mode
file = open (outReport, "w")

#Add Header lines to report text file
file.write("Mains found in this report include:\n")
file.write("Material:" + Qry + "\n")

#Results of SearchCursor
for row in MaterialSearch:
    rptMat = str(row.getValue("Material"))
    rptDiam = str(row.getValue("Diameter"))
    rptSys = str(row.getValue("System"))

    file.write(rptMat + " " + rptDiam + " " + rptSys + "\n")

del MaterialSearch, row
Tags (2)
0 Kudos
18 Replies
Zeke
by
Regular Contributor III
Ian fixed it, but also notice that when you set the SearchCursor, you forgot the with keyword.

Not sure why you set Field twice, but no harm done. Except you have the last quotation mark outside the closing list bracket.
0 Kudos
EstherOlson-Murphy
New Contributor
Thank you Ian!

Things seem to be working better now  (and I saw the missing  keyword too 🙂  )... and I figured out the syntax error as well (brackets in the wrong place!).

Now, though, another error! (shocking 😉  )

This time I am getting with my SearchCursor.

"RuntimeError: cannot open 'G:\Olson-Murphy_Week10\SouthFloridaNaturalGas.gdb\Mains"

I have copied this location out of arcCatalog so I know its not  location issue. I also removed the '-' and '_' and re-pathed everything to make sure that was not the issue.... I'm going to keep fighting with it but any more ideas? 

I hope all you pros are having fun picking apart this easy little script 🙂
0 Kudos
IanMurray
Frequent Contributor
Not sure this is it, but in the error code it threw, it shows a single quote starting your file location and no single quote ending it. 

Also, the file is just a fc in the gdb, not within a feature dataset or anything, if it is, you need to add the feature dataset to your file path.  You shouldn't need to hard code the file path, since you set your environment, it will automatically check that location for the file, so you could do fc = "Mains", though for the sake of this particular script I'd leave it alone til it is working.

Make sure you don't have the file Mains open in ArcCatalog or ArcGIS, it will have a lock on it making you unable to access it with the cursor(I think).

Edit: Haha, yes always lots of error codes.  I always get tons  of them on scripts I write, but it feels to much better by the time works right.  For future reference, I'd write small parts of code at a time, debugging each section as I go.  Once you get one section working, move to the next, it makes it easier to handle errors, and you get small victories as you go, instead of a pile of possible errors at the end.
0 Kudos
EstherOlson-Murphy
New Contributor
Thank you everyone for the help!
I wish I had time time (and skill) to do this in steps to make sure everything worked before moving on but, alas, I do not.
I am still getting the same RuntimeError: Cannot Open "Feature Class" and am unsure why. I have tried double quote, single quotes, full path, just the feature class name, and changed the capitalization still without any luck.

Below is what I am working with. If anyone is REALLY bored and wants data to play with let me know:) ... or if you just see some glaring errors.

At least I am ahead of where I was before.... now at least the header end up in the text time 🙂

Thanks again for all the help



import arcpy
# Set workspace
arcpy.env.workspace = r"E:\OlsonMurphyWeek10\SouthFloridaNaturalGas.gdb"


#Estabslish input feature class
fc = r"E:\OlsonMurphyWeek10\SouthFloridaNaturalGas.gdb\Mains"

# Establish Class fields
fields = ["Material", "Diameter", "System"]

# Establish materials search for tool
Qry ="'Material' = \"Plastic\""

#Define output
outReport = r"E:\OlsonMurphyWeek10\Outputs\Report.txt"

#Open the report text file in write mode
file = open (outReport, "w")

#Add Header lines to report text file
file.write("South FLorida Distrbution Mains:\n")
file.write("Material:" + Qry + "\n")

# Create cursor to search gas mains by material
with arcpy.da.SearchCursor(fc, fields, Qry) as cursor:
  for row in cursor:
    rptMat = str(row.getValue("Material"))
    rptDiam = str(row.getValue("Diameter"))
    rptSys = str(row.getValue("System"))

    file.write(rptMat + " " + rptDiam + " " + rptSys + "\n")

del cursor, row

[\CODE]
0 Kudos
Zeke
by
Regular Contributor III
How about you post your code and data (or a sample), and I'll try to look at it this weekend. Its Fathers day weekend, so can't promise your Sunday deadline, but will try if possible.
0 Kudos
EstherOlson-Murphy
New Contributor
How about you post your code and data (or a sample), and I'll try to look at it this weekend. Its Fathers day weekend, so can't promise your Sunday deadline, but will try if possible.


Thank you so much! that would be great.
Just make sure you don't miss out on Father's Day weekend... its an important one!!

I have attached a zip folder with my data and script. Its all dummy data I made up for the project so its very basic, and there isn't a lot of it 😉

Thanks Again
Esther
0 Kudos
EstherOlson-Murphy
New Contributor
I want to thank everyone again for all the help.
While I may not manage to get this script tool to work for this week's due date, I do hope to use it for a project I am doing for class as well as for work so I am still working at it.

That being said, does anyone know why I would get the error that my feature class cannot be opened? Would this be different than not being able to locate the feature class? As far as I can tell it is not locked and it not opened anywhere accept for in the MXD I am working with. So confused!

Thanks
Esther
0 Kudos
Zeke
by
Regular Contributor III
Esther,

Sorry if this is too late for your deadline, had a busy weekend. I've tried several variations of the script below, which as far as I can see should work, but also getting the can't open error. I'm starting to think it's a problem because (at home) I'm on 10.2, but the data was created in 10.2.1 or 10.2.2, except I see it fine in ArcCatalog. Can't export it, though, so no help there.

What version of Arc are you using? Another possibility is that the gdb or data got corrupted somehow. Can you get a fresh copy? You did a good job setting it up as a tool, so kudos there.

edit: oh, also, wouldn't use 'Expression' with an upper case e, since that comes up as an existing word in intellisense.

import arcpy

fc = r"C:\Test\OlsonMurphyWeek10\SouthFloridaNaturalGas.gdb\Mains"
classField = "Material"
fields = ["Material", "Diameter", "System"]
expression = arcpy.AddFieldDelimiters(fc, classField) + " = 'Plastic'"

#Define output
##outReport = arcpy.GetParameterAsText(1)
outReport = r"C:\Test\Esther.txt"

#Open the report text file in write mode
with open(outReport, "w") as rptFile:
    #Add Header lines to report text file
    rptFile.write("Mains found in this report include:\n")
    rptFile.write(expression + "\n")
print fc
print fields
print expression
# Create cursor to search gas mains by material
with arcpy.da.SearchCursor(fc, fields, expression) as cursor:
    for row in cursor:
        rptMat = str(row.getValue("Material"))
        rptDiam = str(row.getValue("Diameter"))
        rptSys = str(row.getValue("System"))

        rptFile.write(rptMat + " " + rptDiam + " " + rptSys + "\n")

print "Done!"
0 Kudos
EstherOlson-Murphy
New Contributor
Thank you for taking another look at it. While it is a bit frustrating that it doesn't seem to be working i do feel a bit better that, perhaps, it is not me!

I will try to re-create the gdb. Unfortunately I created the data on my own and, stupidly, did not create a back up for it (oh retrospect!). If my new gdb doesn't work i can just recreated the data and try again. I would rather not but it really doesn't take too long to so and, if it means success, I'm game!

Thank you again for taking your time to take a look!
Esther
0 Kudos