Error using SearchCursor to export values to text file

3117
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
The first error message is telling you what's wrong. You trying to use a variable materialType, but haven't defined it. You first need a statement like materialType = 'plastic'. I'm also not sure you should have the % sign right next to the variable name - % materialType instead of %materialType. Maybe that's ok.

You may want to consider the more recent method of formatting strings:
Qry = "Material = {0}".format(materialType)
0 Kudos
EstherOlson-Murphy
New Contributor
The first error message is telling you what's wrong. You trying to use a variable materialType, but haven't defined it. You first need a statement like materialType = 'plastic'. I'm also not sure you should have the % sign right next to the variable name - % materialType instead of %materialType. Maybe that's ok.

You may want to consider the more recent method of formatting strings:
Qry = "Material = {0}".format(materialType)



Thank you for the other option of formatting. I think i like that better!

The way I have to took working I have it so you select the material type you want, its not something I want hard-coded into the scripit. That is what I am trying to to do with that bit of script.

With your formatting string I updated it so I think it should allow me to set the variable in the tool

Qry = "Material = {0}".format(arcpy.GetParameterAsText(0))

but I still get that second error posted above. Any ideas on what that one is? (I have been looking for this answer for a few days so any ideas would be greatly appreciated!)

Thank you!!!
0 Kudos
IanMurray
Frequent Contributor
Hi Esther

Out of curiousity are what version of ArcGIS are you on?  If you are on 10.1 or higher I would highly recommend using the arcpy.da.SearchCursor, since they are faster and the inputs are a little easier to use.

When using the old style cursors, the fields are the 4th parameter, not the third. so you would need a placeholder string between the query and your fields. 

Secondly, the issue is your made your field parameter fields =  "Material;Diameter;System"

This is likely what is causing it to crash, I would either declare the fields to a variable called fields before the cursor or just hard code the fields names in the cursor.  Its looking for a string value, whereas you are making a variable there.

arcpy.SearchCursor(fc,Qry, "",  "Material; Diameter; System")


alternatively:
fields = "Material; Diameter; System"
arcpy.SearchCursor(fc,Qry, "",  fields)
0 Kudos
EstherOlson-Murphy
New Contributor
Ian,
Thank you for this information. Since I am using 10.1 I will have to look at acrpy.da.SeachCursor to see if that makes more sense to me. Unfortunately this is  school assignment, due Sunday AM so I don't have much time to figure it out (plus, sadly, I have already been looking at this for a week!)

Also, than you for the alternatives for seachCursor in terms of how I was identifying the fields to. Unfortunately, after trying both yours suggestions I still got the same error.

Thank you again for help and any other suggestions!
Esther
0 Kudos
Zeke
by
Regular Contributor III
Try printing Qry right after you set it to make sure it has the value you want. Maybe print other values as well.

For Get ParameterByText to work, you need to have made the script a tool, or run it from the command line with arguments. I recommend hard coding some values in for testing. Once it works there, you can switch to parameters.
0 Kudos
EstherOlson-Murphy
New Contributor
Try printing Qry right after you set it to make sure it has the value you want. Maybe print other values as well.

For Get ParameterByText to work, you need to have made the script a tool, or run it from the command line with arguments. I recommend hard coding some values in for testing. Once it works there, you can switch to parameters.



Thank you for reminding me to do this. I have been testing it as a tool (since that is my ultimate goal) but hard coding it is a good idea so I tried that, but now I am getting a syntax error that I cannot figure out. Here is the 'new' code.... syntax Error is associated with #Establish material search for tool: Qry is invalid syntax.


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 Class fields
Field = ["Material", "Diameter", "System]"

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

# Establish Class fields
Field = ["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")

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

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

del Qry, row

0 Kudos
IanMurray
Frequent Contributor
Query expressions can be a bit annoying to put into a python script, especially if you have to store them as a string.

try


Qry ="'Material' = \"Plastic\""



Check this link for more help on building query expressions
0 Kudos
EstherOlson-Murphy
New Contributor
try


Qry ="'Material' = \"Plastic\""



Tried this but still have the same syntax error

exceptions.SyntaxError:invalid syntax (line 13, offset 3) 'Qry ="'Material' = \"Plastic\""'

After all the time I have spent looking at this I have a feeling its a mix of mass confusion on my part and total rookie mistakes.
I have managed to get similar codes to work not as tools, but simply printing the results, but for some reason this one is really fighting me!

Thank you for all the help. As you can tell I'm a little lost and frustrated!
0 Kudos
IanMurray
Frequent Contributor
I see you switched over to arcpy.da.cursor, and that is part of what is causing the new issue.

arcpy.da.SearchCursor(fc,Qry, fields) as Qry:

first parameters is your fc, second parameter is fields (as a list, which you did, great job!), third parameter is the where clause

so it should be


with arcpy.da.SearchCursor(fc, fields, Qry) as cursor:  """(you don't want to use Qry, since that variable is already declared) """
  for row in cursor:
    rptMat = str(row.getValue("Material"))
    rptDiam = str(row.getValue("Diameter"))
    rptSys = str(row.getValue("System"))



I just finished my first python class last semester, and it frustrated a good half of the class alot, especially since almost none of us had a CS background.

Edit: Greg I noticed that extra quotation as well, but I figured she had already gotten past that syntax error, with the error code she was throwing
0 Kudos