I have looked at  and while it is very similar to the question I'm asking I ran into the same issue after implementing its syntax. I feel like I'm still missing something related to how to implement the correct syntax for the below.  where_query = '"field_name" &lt;= ' "{0}.format(year_range)"   I'm trying to make what into a geoprocessing tool that can be reused in ArcMap, but I'm receiving the following error. It looks like an issue with the way that I'm formatting the where_query variable, but I can't seem to get it right.  Traceback (most recent call last):   File "C:\ArcPy\mean_center_drift.py", line 19, in &lt;module&gt;     arcpy.Select_analysis(in_feature, year_out_name, where_query)   File "c:\program files (x86)\arcgis\desktop10.3\arcpy\arcpy\analysis.py", line 84, in Select     raise e ExecuteError: ERROR 000358: Invalid expression 1 Failed to execute (Select).   and here is the code in its current form.  import os import arcpy  in_feature  = arcpy.GetParameterAsText(0) out_features  = arcpy.GetParameterAsText(1) origin_year = arcpy.GetParameterAsText(2) field_name = arcpy.GetParameterAsText(3)  for x in range(10, 140, 10):     year_range = int(origin_year) + x     where_query = '"field_name" &lt;= ' "{0}.format(year_range)"      year_out_name = os.path.join(out_features, "Years_{0}".format(x))     mean_out_name = os.path.join(out_features, "Mean_{0}".format(x))      arcpy.Select_analysis(in_feature, year_out_name, where_query)      arcpy.MeanCenter_stats(year_out_name, mean_out_name, "#", "#", "#")
38834
I am trying to loop through a shapefile, selecting each feature in turn and copying it to a temporary shapefile to by included in a union analysis. I'm using a cursor to find the ID name for each feature which I'm setting to a varible 'Name'. Whenever I try to use this variable as part of the where clause in arcpy.Select_analysis I get an error:   ExecuteError: ERROR 999999: Error executing function. An invalid SQL statement was used. An invalid SQL statement was used. Failed to execute (Select).  The code I'm using is:  Name = 101 where = "\'\"StudyID\" = \\'"+str(Name)+"\\'\'" arcpy.Select_analysis("C:\\input.shp", "C:\\output.shp", where)   If I type it out without using the variables:  arcpy.Select_analysis("C:\\input.shp", "C:\\output.shp", '"StudyID" = \'101\'')   it works fine  What to I need to do to fit the variable into the sql statement?
32433
I'm using field calculator in ArcGIS Desktop 10.2.1.  I have field1 which has a values of "A_B" (example).  I created two fields out of this, values to the left of the underscore go in fielda and to the right of the underscore go in fieldb.  I used the code below in field calculator to separate them out into two fields.  fielda =  field1.split("_")[-1]   fieldb =  `field1.split("_")[-1]`   I now have field1 with values of A_B_C_D.  I need to separate the A_B_C_D into four separate fields using field calculator.  fielda = A, fieldb = B, fieldc = C and so on. I'm not sure how to go about this.  I basically need to parse the values by the underscore.
94464
I have gotten stuck on seemingly simple ArcGIS field calculator python expression.  I obtained a great answer to a another similar question a few years ago: . Now I need to populate a new field based on 6 ranges of values (bedrock depth).  My attempt at writing this expression is below:    I just need to populate the empty field "bedrockdp" using the ranges in the toc called brockdepmin.     Pre-Logic Script Code:  def !GRIDCODE! (value):     if value &gt;0 and value &lt; 50:         return "0 - 50 cm from the surface"     else:         return "n/a"   bedrockdep =  GRIDCODE (!bedrockdep!)
14221
I'm using ArcGIS 10.3.1 for Desktop to test before writing an answer to  I have written the test code below that I am running against a test feature class (testFC) with four line features to try and update its dateField with a constant date value of "01.07.2015".  import arcpy  dmyString = "01.07.2015" fc = r"C:\temp\test.gdb\testFC" item = "dateField"  dmyDate = datetime.datetime.strptime(dmyString,'%d.%m.%Y') print dmyDate  arcpy.CalculateField_management(fc,item,dmyDate,"PYTHON")  with arcpy.da.SearchCursor(fc,[item]) as cursor:     for row in cursor:         print row[0]   I think the above should work, and from the output below you can see that the date object (dmyDate) seems to be created fine, but the values written to each of the four features are not what I would expect.  &gt;&gt;&gt; ================================ RESTART ================================ &gt;&gt;&gt;  2015-07-01 00:00:00 1899-12-30 00:00:00 1899-12-30 00:00:00 1899-12-30 00:00:00 1899-12-30 00:00:00 &gt;&gt;&gt;    Can someone explain why 1899-12-30 00:00:00 is being written instead of 2015-07-01 00:00:00?  The attribute table displays as below:    If I replace the CalculateField line above with either:  arcpy.CalculateField_management(fc,item,"date '2015-07-01 00:00:00'","PYTHON")   or  arcpy.CalculateField_management(fc,item,"date '2015/07/01 00:00:00'","PYTHON")   as per @Vince's comments I receive an error:  Traceback (most recent call last):   File "C:\temp\test.py", line 11, in &lt;module&gt;     arcpy.CalculateField_management(fc,item,"date '2015-07-01 00:00:00'","PYTHON")   File "C:\Program Files (x86)\ArcGIS\Desktop10.3\ArcPy\arcpy\management.py", line 3457, in CalculateField     raise e ExecuteError: ERROR 000539: SyntaxError: invalid syntax (&lt;expression&gt;, line 1) Failed to execute (CalculateField).
51826
I am trying to loop through multiple rasters and extract cells that are above 0.1 The code I am trying to use is:  import arcpy  arcpy.CheckOutExtension('Spatial') arcpy.env.workspace=r'F:\Sheyenne\Atmospherically Corrected Landsat\Indices\Main\NDWI\main_master' #pathway to all rasters in workspace directory rasters = arcpy.ListRasters('*.tif*') for raster in rasters:      #give new file a name      outraster = raster.replace('.tif','_water.tif')      arcpy.gp.RasterCalculator_sa("""raster &gt;= 0.1""",outraster) print('Done Processing')   For some reason I can't copy and paste the error (python actually shuts down when I run this code) but here is a screen shot of part of it.    EDIT: My parameters have changed and I now need everything >=-0.4 and but !=0.00.  I am trying to use:  import arcpy  from arcpy.sa import * arcpy.CheckOutExtension('Spatial') arcpy.env.workspace=r'D:\Sheyenne\Atmospherically Corrected Landsat\Indices\Main\NDWI\main_master' #pathway to all rasters in workspace directory rasters = arcpy.ListRasters('*.tif*') for raster in rasters:     #Save temp raster to disk with new name     ras = Raster(raster)     outraster = Con(ras &gt;= -0.4 &amp; ras !=0.00, ras)     outraster.save(raster.replace('.tif','_water.tif')) print('Done Processing')   but this returns:  ValueError: The truth value of a raster is ambiguous. Invalid use of raster with Boolean operator or function. Check the use of parentheses where applicable.   EDIT:  I think I just needed to change this line:   outraster = Con((ras &gt;= -0.4) &amp; (ras !=0.00), ras)
8784
My script works fine with a single feature class selected for clip_fc = arcpy.GetParameter(0) .  However when I set clip_fc to MultiValue in the script properties and then select several feature classes, I get an error "Parameters are not valid.".   Can anyone show me where I am going wrong?  import arcpy import os.path from arcpy import env  arcpy.env.workspace = r"C:\GIS Home\project_1\clipshps\Combined_mf.gdb" arcpy.env.overwriteOutput = True clip_fc = arcpy.GetParameter(0) clip_name = str(clip_fc) output_dir = r"C:\GIS Home\project_1\clipshps\outputs_clip"  for fds in arcpy.ListDatasets():     for fc in arcpy.ListFeatureClasses('','',fds):         out = os.path.join(output_dir, fc + "_" + clip_name[40:] + "_clip.shp")         arcpy.Clip_analysis(fc, clip_fc, out, "")
76447
I am trying to export/copy a feature service to a local geodatabase where I can work on it locally.    I have provided the code below. I keep getting an "Object: Error in executing tool" for the last line where I am trying to copy the feature.   from arcgis.gis import GIS from arcgis.features.use_proximity import create_buffers  import arcpy  #########################################################################################  GDB_Name = input("Name Geodatabase")  Folder_Input = input("Provide Folder Path of Project")  Item_ID = input("Provide item ID")   #########################################################################################  gis = GIS("http://arcgis.com", "XXXXXXXX", "XXXXXXXXXXX")  search_results = gis.content.search('{}'.format(Item_ID))  Trail_Data = search_results[0]  WorkspaceGDB = arcpy.CreateFileGDB_management(Folder_Input, '{}.gdb'.format(GDB_Name)) print("GDB created")  arcpy.env.workspace = r'{}'.format(WorkspaceGDB)  arcpy.CopyFeatures(Trail_Data, "Area_Trail_Data")
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.
97720
I'm using the following python code to replace Null values by 0, using field calculator:  def nulls(p1):  if p1 is None:     return 0  else:     return p1   But nothing happens, Null values stay. I'm using ArcGIS Desktop 10.0.
69493
I have a paradox table from a legacy system I need to run a single query on.  The field names have spaces in them - i.e. "Street 1".  When I try and formulate a query in delphi for only the "Street 1" field, I get an error - Invalid use of keyword. Token: 1, Line Number: 1  Delphi V7 - object pascal, standard Tquery object name query1.
83114
In ArcGIS 10.5, I am building a model that should convert a field of coded values to another code. This seems like it should be a simple if/then statement but I am not getting it. To simplify the process, I populated the target field with the source field's values and then intend on using python to transpose the values. It should be considered a string, but the values are numerical. The field I am trying to edit is "TP_Condi"   In the "Calculate Field" code block:  def reclass:   if TP_Condi = 3:          return 1     elif TP_Condi = 2:           return 8   elif TP_Condi = 1:          return 3   else:          return "error"      This is the code I was seeking:
87934
I am making my first attempt at editing an ArcSDE feature class with python through a da.UpdateCursor. I'm essentially taking code I've written for a file geodatabase feature class and applying it to an SDE feature class. Doing so produces an error, and I'm not sure how to rectify the problem.   I'm using ArcGIS 10.1 for Desktop.  Pertinent code:  Struxfeature = r"DatabaseConnections\PipelinePathways.sde\PPGIS.Strux\PPGIS.StruxPts_v04_all" P6feature = r"DatabaseConnections\PipelinePathways.sde\PPGIS.Strux\PPGIS.Land_Projects_Parcels_P6"  SDE = r"Database Connections\PipelinePathways.sde" UserID = "E1B8" Parent = "SDE.DEFAULT" version = "change_RW_VC_4447_14_to_C"  #Create Version print "Creating version" arcpy.CreateVersion_management(SDE, Parent, version, "PUBLIC") VersionName = UserID.upper() + "." + version  #Layers arcpy.MakeFeatureLayer_management (Struxfeature, "Struxlyr") arcpy.MakeFeatureLayer_management (P6feature, "P6lyr")  #Switch to version print "Switching version" arcpy.ChangeVersion_management("Struxlyr", "TRANSACTIONAL", VersionName) arcpy.ChangeVersion_management("P6lyr", "TRANSACTIONAL", VersionName)  #Start editing print "Initiating editing" edit = arcpy.da.Editor(SDE) edit.startEditing()  # Start an edit operation edit.startOperation()   #Change P6 project numbers    print "Updating P6.\n" P6Cursor = arcpy.da.UpdateCursor ("P6lyr", ["P6_NBR", "Name"]) for row in P6Cursor:     codecodecode   The error comes from the line 'for row in P6Cursor:'  Traceback (most recent call last):   File "C:\E1B8\ScriptTesting\ScriptsIUse\ChangeP6.py", line 81, in &lt;module&gt;     for row in P6Cursor: RuntimeError: workspace already in transaction mode
74695
I'm using ArcGIS for Desktop 10.3.0.4322 I have a script tool which requires a parameter (folder path to a gdB, via GetParameterAsText) so that a later process can be saved there. The thing I want to do is make an Optional Boolean parameter, that when checked, automatically fills in the folder path gdB parameter. The Boolean text asks the user, &quot;Use default workspace?&quot;, to which if they check the box (boolean == True), then the folder path parameter will be automatically defaulted (saving the user a small amount of time). I have already created the Boolean parameter in the script tool, I am however unaware of how to &quot;fill in&quot; the required parameter based on the user's Boolean. Code Snippet: # Ask user to select the Geodatabase workspace to use for data output userWorkspace = arcpy.GetParameterAsText(0)  # Ask user if they want to use default workspace (boolean) useDefault = arcpy.GetParameterAsText(1)  # If user wants default workspace, then give it to the required parameter (0) if useDefault == True:  arcpy.env.workspace = path else:  # Set workspace environment based upon user's choice  arcpy.env.workspace = userWorkspace
47699
I have  a series of polyline shapefiles and I am trying to automate the process of calculating the X and Y coordinates of the line start and line end using Python.  I have added the 4 fields (startx, starty, endx, endy) in Python with the following code:  Arcpy.addfield_management ("Polyline","startx","DOUBLE")   I can perform this task by right-clicking the attribute and calculating geometry, but I want to automate this process for about 30 polylines.  I have the following code I've found that might be able to perform the desired task with some modification:  xExpression = "float(!SHAPE.CENTROID!.split()[0])" yExpression = "float(!SHAPE.CENTROID!.split()[1])"  arcpy.CalculateField_management("Polyline", "startx", xExpression, "PYTHON") arcpy.CalculateField_management("Polyline", "starty", yExpression, "PYTHON")   This code only calculates the coordinate at the centre of the shape I believe. Are their any expressions I can add to this code to calculate the X and Y coordinates of the start and end points of the polyline?  I am using ArcGIS 10.1 with ArcInfo license.
84571
I am having some difficulties to change "NULL" values to zero in geodatabase. I have tried the following python code in ArcGIS 10.1 ("Field Calculator") to change it but did not work.   Pre-Logic Script Code:  def RemoveNULL(x):     if x is None:         return ''     elif x == '':         return '0'     else: return x   Calculation field:  RemoveNULL(str( !DEAD_VOL_PER_HA_SPP1_125!))   Error message:  ERROR: 999999: Error executing function The value type is incompatible with the field type. [dead_pine] Failed to execute (calculate field)
104164
I'm new to ArcGIS 10 and am trying to do a really simple field calculator equation and it is not working. I'm just trying to find the percentage of a certain demographic trait by doing:  [asian]/[total]*100   It is populating about 10% of the column correctly and then I get an error:     There was a failure during processing, check the Geoprocessing Results   window for details   Obviously my syntax is not incorrect or else it wouldn't start populating the field correctly.   Does anyone have any idea why this is happening?
103465
Using ArcGIS ArcMap 10.6: I have a text field in an attribute table that has comma separated values (example: 12,24, 64, 87,29). For this example, I will name this field VALUES. Please note that VALUES includes data collected from field work so the spacing between commas will be varied. My current workflow is as followed:  Export the ID and VALUES fields in the attribute table into a .csv file using Table to Table in ArcMap 10.6 Open the .csv in Excel and run the 'text to columns' function under the Data ribbon Separate the VALUES field into multiple columns based on commas Run the calculation: Copy Column I values and ID columns into a new .csv file Save and close the new .csv file and join the shapefile to the new .csv file based on ID Export the newly joined shapefile into a new file and delete the duplicate ID field in the new shapefile  I am wondering if there is a way to automate this Python/ArcPy so I can create a custom script tool to do this without leaving the ArcGIS environment. Is there a way to separate values in a text field based on commas into different columns, run the above calculation, and have the values from that calculation entered in a new field named VALUES_CALCULATED?