I am trying to find whether any feature classes in multiple gdb's has Feature class representation. If a feature class has represenation, "RuleID" &amp; "override" fields will be in the attribute table. So i am just checking whether these two fields are present in the attribute tables.   This code is printing the results. But also returning few errors. Don't know whats the problem.  import arcpy  def FindField(fc,myField):         fieldList = arcpy.ListFields(fc)         for field in fieldList:             if str.lower(str(field.name)) == str.lower(myField):                 print "    " + fc + " contains fieldname: " + myField  def FindField2(fc,myField2):         fieldList = arcpy.ListFields(fc)         for field in fieldList:             if str.lower(str(field.name)) == str.lower(myField2):                 print "    " + fc + " contains fieldname: " + myField2   myField = "RuleID" myField2 = "Override" dir = r'D:\Test\gdb' arcpy.env.workspace = dir  gdbList = arcpy.ListWorkspaces('*','FileGDB')  for gdb in gdbList:     arcpy.env.workspace = gdb                    datasetList = arcpy.ListDatasets('*','Feature')          fieldList = arcpy.ListFeatureClasses()              for fc in fieldList:         print arcpy.env.workspace,fc         print "Searching root level Featureclasses..."         print "  Searching " + fc         FindField(fc,myField)         FindField(fc,myField2)      for dataset in datasetList:         arcpy.env.workspace = dataset            fieldList = arcpy.ListFeatureClasses()              for fc in fieldList:             print arcpy.env.workspace,fc             print "  Searching Featureclass... " + fc             FindField(fc,myField)             FindField(fc,myField2)  D:\Test\gdb\RT_FactGeology_Qld_25K.gdb Rio_FactGeology_Qld_L Searching root level Featureclasses... Searching Rio_FactGeology_Qld_L Rio_FactGeology_Qld_L contains fieldname: RuleID Rio_FactGeology_Qld_L contains fieldname: Override  D:\Test\gdb\RT_Roads_Qld_25K.gdb Rio_Roads_Qld_L Searching root level Featureclasses... Searching Rio_FactGeology_Qld_L Rio_Roads_Qld_L contains fieldname: RuleID Rio_Roads_Qld_L contains fieldname: Override  Runtime error  Traceback (most recent call last): File "&lt;string&gt;", line 31, in &lt;module&gt; File "&lt;string&gt;", line 6, in FindField UnicodeEncodeError: 'ascii' codec can't encode character u'\xf3' in position 7: ordinal not in range(128)
123507
I have done it many times (clipping a raster with a polygon layer or by extension) but today I got an error for the first time and I don't know how to solve it. I am always using the same type of raster layers. When running the clipping tool I got the following message:  gdal_translate -of GTiff -ot Byte -projwin 410282.185971 4694950.41162 410783.882475 4694524.96815 -co COMPRESS=DEFLATE -co PREDICTOR=1 -co ZLEVEL=6 -co TFW=YES "C:/Users/FERRAN ALA/Desktop/Justificació Fontanals/QGIS/Topo 1_5000/bt5mv20sd0f283077st1r031.sid" "C:/Users/FERRAN ALA/Desktop/Justificació Fontanals/QGIS/background/image.tif"   GDAL command output:     'ascii' codec can't encode character u'\xf3' in position 201: ordinal not in range(128) See log for more details   Does anybody know what that is?
1526
I am attempting to use this code in a tool that I am working on:  mxd = arcpy.mapping.MapDocument("CURRENT") df = arcpy.mapping.ListDataFrames(mxd)[0] XMIN = df.extent.XMin YMIN = df.extent.YMin XMAX = df.extent.XMax YMAX = df.extent.YMax   I then go on to do other calculations with the extent. The code works perfectly in the Python window, but because Toolbox tools are run in separate processes I am unable to use "CURRENT".  I think I could probably add a derived input variable and pass the coordinates through the validation script, but that doesn't work for what I am doing. I need to be able to do this later on in the script and add an additional temporary feature to the current map:  points = arcpy.CreateFeatureclass_management("in_memory", "NewFeature", "POINT") arcpy.AddField_management(points, "NewField", "TEXT", "", "", 20)   I know all of my code works right, because I can paste the entire .py into the  Python window and then call Main() and run through it, but I need to share it with others in an easier way.   I would prefer the solution be compatible with 10.0 and 10.1 if at all possible, because some of the people I work with do not have 10.1 yet. I will accept a 10.1 only solution if I have to though.  What options do I have to do this?    I still can not get this to work, they have not gotten me Python Add-In Wizard yet so I am unable to test that approach. I have again tried the "Run in process" box checked and unchecked. Neither are working.   Checked gives me this: RuntimeError: CreateObject cannot open map document  Handled that exception: Object: CreateObject cannot open map document  From my testing looks like it is having the same error running in process or not.    I will still be attempting to do this within the Add-In Wizard, when they finally give me it.  The winning answer is I wasn't running it in the foreground.
75457
I am trying to populate a field with corresponding file name. For example, if the file name is Route1.shp then the field value will be Route1 as well. However my code is not working. Can you please suggest a code that works? The code I used is given below, along with the error message             import arcpy, os, sys     from arcpy import env     arcpy.env.overwriteOutput = True     env.workspace = r"C:\ABC\GIS"     fc_tables = arcpy.ListFeatureClasses ("R*")     for fc in fc_tables:         field = "RouteName"         arcpy.AddField_management (fc, field, "TEXT")     for fc in fc_tables:     arcpy.CalculateField_management (fc, field, str(fc), "PYTHON")   And this is the error message     Runtime error  Traceback (most recent call last):   File "",   line 2, in    File "c:\program   files\arcgis\desktop10.1\arcpy\arcpy\management.py", line 3128, in   CalculateField     raise e ExecuteError: ERROR 000539: Error running   expression: Route1.shp  Traceback (most recent call last):   File   "", line 1, in  NameError: name 'Route1' is not   defined  Failed to execute (CalculateField).
78606
I'm just starting to get into Python scripting for work.  I'm currently creating a script to automate a process.  Basically, it asks the user the client name, gets a projection if available, creates directory on C: drive for client, creates file geodatabase specific to client, creates required dataset, and creates feature classes specific to clients data. Eventually, it will also add the required fields to each feature class and probably some other things.  I started this not really knowing the proper etiquette of Python scripting for ArcMap. But what I've created so far will only run outside ArcMap I believe.   Is this acceptable?   Instead of getting user input through arcpy.getparamaterastext(), which I just found out about, I'm using raw_input().   Is this okay?   It does work, I'm just not sure if this is a proper way to do scripting.  Here's the code I have so far.  import sys import arcpy import os  #Records name of the client client = raw_input("Enter the name of the client: (letters and underscores only) \n")  #Records filepath of client to be created clientpath = "C:/" + client  #Inquires if projection file exists projection = raw_input("Is there a .prj or .shp available with correct projection? Y or N \n")  #Records the projection location if available if projection.upper() == "Y":     spatialr = raw_input("Drag the .prj or .shp here to record the filepath \n")     nspatialr = spatialr.replace('"', "") elif projection.upper() == "N":     alert = raw_input("You must add the spatial reference manually, hit enter to continue. \n") elif projection.upper() != "N" or "Y":     exit = raw_input("That is not a valid response. Try again. \n")     sys.exit()  #Checks if client folder exists; if not, creates one if not os.path.exists(clientpath):     os.makedirs(clientpath)  #Variable for file geodatabase location FGBpath = clientpath + "/" + client + ".gdb"  #Checks if client file geodatabase exists; if not, creates one if not arcpy.Exists(FGBpath):     arcpy.CreateFileGDB_management(clientpath, client)  #Variable for dataset location FDatasetpath = clientpath + "/" + client + ".gdb" + "/Network"  #Checks if dataset exists; if not, creates one if not arcpy.Exists(FDatasetpath):     if projection.upper() == "Y":         arcpy.CreateFeatureDataset_management(FGBpath, "Network", nspatialr)     elif projection.upper() == "N":         arcpy.CreateFeatureDataset_management(FGBpath, "Network")  #Variable for cable feature class location FCcablepath = clientpath + "/" + client + ".gdb" + "/Network" + "/cable"  #Checks if cable feature class exists; if not, creates one if not arcpy.Exists(FCcablepath):     if projection.upper() == "Y":         arcpy.CreateFeatureclass_management (FDatasetpath, "cable", "POLYLINE", "", "", "", nspatialr)     elif projection.upper() == "N":         arcpy.CreateFeatureclass_management (FDatasetpath, "cable", "POLYLINE")  #Variable for splice point feature class location FCsplicepath = clientpath + "/" + client + ".gdb" + "/Network" + "/splice_point"  #Checks if splice point feature class exists; if not, creates one if not arcpy.Exists(FCsplicepath):     if projection == 'Y' or projection == 'y':         arcpy.CreateFeatureclass_management (FDatasetpath, "splice_point", "POINT", "", "", "", nspatialr)     elif projection == 'N' or projection == 'n':         arcpy.CreateFeatureclass_management (FDatasetpath, "splice_point", "POINT")  exit = raw_input("\n\n File geodatabase, dataset, and the cable \n and splice point feature classes successfully created. \n\n Hit enter to exit.")   I still have some work to do, like adding the needed fields.
110247
I'm trying to pass an in memory layer object created from a feature class using Code:  arcpy.MakeFeatureLayer_management()   into the Code:  arcpy.mapping.ExportReport()   function. It's erroring out, so I think it's having trouble with the in memory feature layer (Does a feature layer have a.lyr extension?).  My code is:  Code:  arcpy.MakeFeatureLayer_management("SOILFC", "soil.lyr") arcpy.mapping.ExportReport("soil.lyr", reportfilename, r"C:\Test_Outputs\ProjectReport1.xls")   I'm not sure if the mapping class needs an actual map document to work on, but I'm hoping not. I don't want to go through the process of creating a temp .mxd, setting a dataframe reference and then add in some layers somewhere just for the purpose of getting a layer object to create a report. I was just hoping I could create the report using in memory objects because the only thing I care about if the .xls report from the final output.
35922
I have a handy script tool that loops through a workspace and renames and copies shapefiles to a feature dataset.  However, if there is a corrupted shapefile somewhere in the workspace the script fails and stops processing.    How do you handle errors such as this?  Is there a way to print the error file and continue processing the next shapefile in the for loop to completion?   import arcpy from arcpy import env  # Allow overwriting of output   env.overwriteOutput = True  # Parameters   env.workspace = arcpy.GetParameterAsText(0)  state = arcpy.GetParameterAsText(1) gdb = arcpy.GetParameterAsText(2)  # Get a list of shapefiles in folder   fcs = arcpy.ListFeatureClasses()   # Find the total count of shapefiles in list   fcCount = len(fcs)   # Set the progressor  arcpy.SetProgressor("step", "Copying shapefiles to geodatabase...", 0,fcCount, 1)   # For each shapefile, copy to a file geodatabase  try:     for shp in fcs:            # Define name for the output points          fc = str(state + shp[0:9])          # Update the progressor label for current shapefile           arcpy.SetProgressorLabel("Loading " + shp + "...")           # Copy the data           arcpy.CopyFeatures_management(shp, str(gdb + "\\" + fc))           # Update the progressor position           arcpy.SetProgressorPosition()  except Exception as e:     print "An error has occurred"     print e  arcpy.ResetProgressor()
22870
I have question about ArcGIS and python script. There are following sample code, So I would like to change Another Field , not OIDFieldName. Please let me know how to change Another Field.  import arcpy import itertools  arcpy.env.workspace = r"C:\path\to\workspace"  base_shapefile = "some_shapefile.shp"  oid_field = arcpy.Describe(base_shapefile).OIDFieldName feature_count = int(arcpy.GetCount_management(base_shapefile).getOutput(0))  for (i, j) in itertools.combinations(range(feature_count), 2):     arcpy.Select_analysis(base_shapefile , "combination_%i_%i.shp" % (i, j), '"%s" in (%i, %i)' % (oid_field, i, j))   These sample code is combination for 5C2. I want to create all combiantions 5C3 , 5C4 , 5C5.
63694
I'm quite new with arcpy and I'm finding selecting by attribute a bit of a nightmare. There's a problem with my query on the script below [query = "\'Location\' = observer"], but I can't tell what it is. 'Location' is a field of the feature class I'm dealing with (fc_copy).  with arcpy.da.UpdateCursor(fc_copy,field_names) as cursor:        for row in cursor:         observer = row[0]         arcpy.MakeFeatureLayer_management(fc_copy, 'fl_copy_OBS')         arcpy.MakeFeatureLayer_management(fc_copy, 'fl_copy_TAR')         query = "\'Location\' = observer"         arcpy.SelectLayerByAttribute_management('fl_copy_OBS', 'NEW_SELECTION', query)         arcpy.SelectLayerByAttribute_management('fl_copy_TAR', 'NEW_SELECTION', query, invert_where_clause = 'INVERT')   This is the error I get => Invalid expression                            Failed to execute (SelectLayerByAttribute).  Is there any documentation to learn the rules to follow to build queries for arcpy?
64609
I have taken three fields from case object called AccountName, IntegrationTo__c and SfType__c (checkbox).  I have created one case record with a specific combination of three fields.  For the second time I create a record with that combination, then  display error message only if SfType__c is true in first record otherwise allow  for record creation.  trigger AvoidDuplicate on Case(before insert)  {          set&lt;string&gt; newNameSet = new set&lt;string&gt;();     newNameSet = new set&lt;string&gt;();      set&lt;string&gt; newEmailSet = new set&lt;string&gt;();      set&lt;string&gt; dbNameSet = new set&lt;string&gt;();      set&lt;string&gt; dbEmailSet = new set&lt;string&gt;();      for(Case newLead : trigger.new){          newNameSet.add(newLead.Account.Name);          newEmailSet.add(newLead.IntegrationTo__c);      }      for(Case dbLead : [select id, Case.Account.Name, IntegrationTo__c from Case where IntegrationTo__c IN: newEmailSet OR Case.Account.Name IN: newNameSet]){          dbNameSet.add(dbLead.Account.Name);          dbEmailSet.add(dbLead.IntegrationTo__c);      }      for(Case newLead : trigger.new){          if(dbNameSet.contains(newLead.Account.Name) &amp;&amp; dbEmailSet.Contains(newLead.IntegrationTo__c))              newLead.addError('You are inserting Duplicate Case');      }  }   i wrote this this not checking the account field name and integration__c values only with combination of account and integration__c shows error
119738
In the attached screenshot, the attributes contain two field of interest "a" and "b".  I want to write a script to access the adjacent rows in order to make some calculations.  To access a single row, I would use the following UpdateCursor:  fc = r'C:\path\to\fc'  with arcpy.da.UpdateCursor(fc, ["a", "b"]) as cursor:      for row in cursor:           # Do something   For example, with OBJECTID 4, I am interested in calculating the sum of the row values in field "a" adjacent to OBJECTID 4 row (i.e. 1 + 3) and adding that value to the OBJECTID 4 row in the "b" field.  How can I access adjacent rows with the cursor to make these sort of calculations?
96510
I have a python addin, which as part of its function checks to see if a template point feature class exists on the user's machine.  If it doesn't, it creates this file.  This template file is used elsewhere in the addin to create other files.  I do not want this template file to be added to the map document.  When the addin is run, if the template file doesn't exist it gets created and automatically added into the currently active data frame.  Is there something I can add to the scrip to prevent this from happening?  Or is the neatest way to let the feature class be added to the data frame and then add a line to the script to remove it from the map document?  My code is currently as follows:  coordsys = arcpy.SpatialReference(27700)  #Define the schema file for the output schemafile = defgdb + "/Template"  #Check to see if the schema file exists, if it doesn't, create it. if arcpy.Exists(schemafile):     pass else:     arcpy.CreateFeatureclass_management(defgdb, "Template", "POINT", "", "", "", coordsys)   My current method for removing the layer from the map document (rather than preventing the layer from being added) is:  for layer in arcpy.mapping.ListLayers(mxd, "Template"):     arcpy.mapping.RemoveLayer(df,layer)
63333
My code will not project and store the feature layer in the scratch.gdb. "ERROR 999999 ... The table name is invalid. The table was not found. [17_5330_51961Lake]"  The interpreter doesn't like "-" characters or beginning or ending in a number. Does anyone know of a work around?  import arcpy import os  mxd = arcpy.mapping.MapDocument("Current") mxdpath = mxd.filePath (filepath, filename) = os.path.split(mxdpath) MCP_Path = str(filepath)  srl = os.path.join(MCP_Path, r"CoordinateSystems\NAD 1983 UTM Zone 17N.prj")  WBYLID = "17-5330-51961"  WBYLIDlabel = WBYLID.replace("-","_")  LakeOut = os.path.join(MCP_Path + "\OutputData\Scratch.gdb", WBYLIDlabel + "Lake") arcpy.Project_management(fl, LakeOut, srl)
91640
I have a model class:  class Person(db.Model):   first_name = db.StringProperty(required=True)   last_name = db.StringProperty(required=True)   I have an instance of this class in p, and string s contains the value 'first_name'. I would like to do something like:  print p[s]   and   p[s] = new_value   Both of which result in a TypeError.  Does anybody know how I can achieve what I would like?
112923
Can someone help me understand what the last 2 lines of this code does:  import arcpy arcpy.env.workspace = "c:/esripress/python/data/exercise07" arcpy.env.overwriteOutput = True  copy = arcpy.CopyFeatures_management("airports.shp","Results/airports.shp") fc = "Results/airports.shp"  cursor = arcpy.da.UpdateCursor(fc, ["STATE"], ' "STATE" &lt;&gt; \'AK\'') for row in cursor:     row[0] = "AK"     cursor.updateRow(row) del row del cursor   I understand that the loop function goes through each record that does not have a value of 'AK'  and gives that record a value of "AK".  But what I don't understand is what the del row and del cursor are meant to do.
98138
In Python, I can do:  &gt;&gt;&gt; list = ['a', 'b', 'c'] &gt;&gt;&gt; ', '.join(list) 'a, b, c'   Is there any easy way to do the same when I have a list of objects?  &gt;&gt;&gt; class Obj: ...     def __str__(self): ...         return 'name' ... &gt;&gt;&gt; list = [Obj(), Obj(), Obj()] &gt;&gt;&gt; ', '.join(list) Traceback (most recent call last):   File "&lt;stdin&gt;", line 1, in &lt;module&gt; TypeError: sequence item 0: expected string, instance found   Or do I have to resort to a for loop?
45045
I am a beginner to python coding in GIS. I want to calculate the total number of counts in raster attribute table. In order to do that:   I would like to build a attribute table of raster data use a loop through attribute table using ARCPY.SearchCursor()   Therefore, I wrote a code to build an attribute table. However, I am getting an error while running the code and not able to figure out the error in the code.  Code:  import arcpy # Create the geoprocessing object  import arcgisscripting gp = arcgisscripting.create()  #To overwrite output arcpy.env.overwriteOutput = True  #Set environment settings gp.workspace = "C:/Subhasis/Test/raster-read"  #Build Raster Attribute Table gp.BuildRasterAttributeTable_management("sti-9", "Overwrite")  Error Message: Traceback (most recent call last):   File "C:/Subhasis/Test/raster-read/test.py", line 15, in &lt;module&gt;     gp.BuildRasterAttributeTable_management("sti-9", "Overwrite") ExecuteError: ERROR 000049: Failed to build attribute table Failed to execute (BuildRasterAttributeTable).
43346
How do you calculate fields with null values?  I have multiple fields that may have null values, that aren't being calculated in the third field.    import arcpy with arcpy.da.UpdateCursor(r"...gdb\test.gdb\test",["A", "B", "C"]) as cursor:     for row in cursor:         row[2] = row[0] + row[1]         cursor.updateRow(row)   The result of that calculation is this error:  Traceback (most recent call last):   File "C:\Users\Desktop\updatecursor2.py", line 4, in &lt;module&gt;     row[2] = row[0] + row[1] TypeError: unsupported operand type(s) for +: 'NoneType' and 'float'   The result of the script are the same results when I try to use the field calculator:    How do you use the data update cursor, or field calculator to calculate the sum of the values in a new field if you have null values?  I'm using ArcGIS 10.1 SP1 for Desktop.