New answers tagged

2

I have found the solution to my problem. Instead of referencing the dataset within the geodatabase, simply reference the geodatabase. For example: # workspace = output + "\\PlanningSession.gdb\\DIDs" ## Referencing the Feature Dataset workspace = output + "\\PlanningSession.gdb" ## Referencing the GDB lyr = ...


1

You can circumvent the error of the deep deep folders / file path longer than 255 characters in two ways in Python. One way is to use the win32api and get a short representation of the long filepath. From what I understand this is also what WinExplorer does internally. from win32api import GetShortPathName long_path = ...


0

There are two answers depending on your definition of distance: bird's flight or along the road. they wil be identical on a straight line but differ on curves or broken lines. bird's flight you could create a buffer around your point, then intersect the buffer geometry with the line. You can do this for all your points at once using the geoprocessing tool ...


1

I changed this line arcpy.FeatureclassToCoverage_conversion(in_features="'"+arcpy.env.workspace+"\\lines' ARC;'"+arcpy.env.workspace+"\\points' POINT;",out_cover=coverageOutDir) to this arcpy.FeatureclassToCoverage_conversion(in_features="'lines' ARC; 'points' POINT;",out_cover=coverageOutDir) and it worked. :)


0

The solution was to use a SearchCursor and an InsertCursor to copy the data from the event layer to the feature class. This solution was found here. It is multple times faster than the arcpy.CopyFeatures_management tool.


1

I hope I understood your problem sufficiently. As far as I got it, I would try the following: # predefine the constant parts of your expression using a variable: constant = "\ftp\raw\YYYYMMDD\Files\Charles" nameVar = "yourobject.Name" # use the built in function .format for setting up the expression for your arcpy.CaculateField_management function: ...


0

As commented by the asker, this was their solution: I have solved the problem. All attempts inside the geoprocessing (arcgisscripting) failed even if I constructed completely new objects from scratch setting vertices' coordinate values. So, I resorted to Osgeo.ogr library to create new shape file. The data had been imported using WKT data format ...


7

The output you are receiving is correct. Assuming you have two polygons, one without a hole, and one with a hole, then each of these shapes is single-part. Polygon geometry has two levels of construction - parts and rings. Each part must have one exterior ring, but may contain additional interior rings (aka "holes"). The partCount property returns the ...


7

Try placing the wellCntList list outside of the for loop. Otherwise, each iteration is writing over the results of the previous one--ultimately leaving only the last iteration's results. wellCntList = [] for cname in countyList: whereclause = "{} = '{}'".format("COUNTY", cname) wellCnt = 0 with arcpy.da.SearchCursor(Wells_Intersect_Layer, ...


0

okay, since Richard answered frist, I played around with his approach first. Can't get it to work though. I set up the global parameter right at the start of the code (before class ToolValidator) and tried to get it in the function updateParameters by adding "global lastChecked" inside the updateParameters. import arcpy lastChecked = 0 # here I set up the ...


2

a global variable gives me an error, but i didn't looked further, because i thought of another approach. Given a Script-Tool with three checkboxes (boolean parameter 0,1,2) i added a fouth parameter (long) which stores the users choice. This one you can also evaluate in the Tools Python script. One problem remains: a checkbox can be unchecked, so i decided ...


2

Try setting it up this way. Define a lastChecked global variable to hold the value of 0 to represent the first checkbox and by default make sure the first check box is checked at tool initialization. First check if the user set all checkboxes to False, and if they did, reset the lastChecked checkbox back to True (radio buttons cannot be turned off by ...


3

I would encourage you to follow the more modern Update Cursor syntax. The following script should get you started. In this example, There are two fields "field1" and "FERRY". If "ferry crossing" is in "field1", the "YES" will be added to the "FERRY" field, otherwise "NO". import arcpy fc = r'C:\path\to\your.gdb\feature_class' with ...


2

I use the following code, which copies values from fields on From/To points into From/To fields against each line (different fields if start or end point). This runs on selected lines, but can be easily modified to run on all lines. import sys, string, os, arcpy, fpformat mxd = arcpy.mapping.MapDocument("CURRENT") layers = arcpy.mapping.ListLayers(mxd) ...


2

You are missing a + after +str(year) at the end line. Should be: arcpy.gp.Reclassify_sa("F:/Dissertation/0201_HysplitOutputs/LAI_calc/FINAL/"+month+"_"+str(year)+"_LAI_CALC","VALUE","2 28 1;28 56 2;56 84 3;84 112 4;112 140 5;140 168 6;168 196 7;196 224 8","F:/Dissertation/0201_HysplitOutputs/LAI_calc/FINAL/"+month+"_"+str(year)+"_LAI_FINAL","DATA") ...


5

The problem was that I had null values. Make sure to check your data for null/nil values! if row[1]: startptx = row[1].firstPoint.X else: print "There are null values in your data"


1

So I figured it out - @Yanes was close but instead of three sets of double quotes, it needed to be double-single-double. So the following script works: -- Turn ReportsTable into a View Table arcpy.MakeTableView_management(ReportsTable, ViewTable) -- Get start and end times for report start_time= datetime.timedelta(hours = 24) end_time = ...


1

From the ListFields help you will see that the syntax for that function is: ListFields (dataset, {wild_card}, {field_type}) The only required parameter is dataset which is explained as: The specified feature class or table whose fields will be returned. You received that particular error because you did not provide a feature class or table and ...


3

I know error messages have a bad vibe about them, but they really do represent an effort to explain what has gone wrong, so it's worth an effort to ask, "Well, what does that mean?" In this case, the line of code is: fields = arcpy.ListFields(fcList) and the error says: "[u'Hospitals',u'Parcels',u'Roads']" does not exist This indicates that a list ...


1

Try wrapping your Where statement with three double quotations so that Arcpy understands it as an expression for your select function not a standalone SQL task - I may be wrong on the reasoning, I will check. SQL = """ "created_date" >= '{}'""".format(report_time.strftime('%Y-%m-%d %H:%M:%S')) ...


3

Once you did your analysis you can Copy your output with arcpy.CopyRaster_management. Where you can specify bit depth through the pixel_type arg. For example - arcpy.CopyRaster_management("inrast","outrast","","","-9999", "","","8_BIT") You can then delete the earlier output to cleanup.


1

The major issue you are missing is that the ObjectID column is not intended to be used as an identifier column. It is not necessarily a static number. It is possible that the powers that be at your workplace know that and are keeping that in mind in their workflow. On the other hand, you might want to make sure they know that if anyone edits the data or ...


5

FeatureClassToFeatureClass_conversion is the equivalent tool for the ArcGIS desktop export data function. It almost never is a good idea to use ObjectId as a user reference. Why don't you generate a user id column which you know will be consistent through data exports?object Ids within a gdb are given in reference to other features in feature classes stored ...


0

You can use JoinField_management to join the table in which you have the schema to the Feature Class that has no fields defined. If you join by OBJECT_ID, the Feature Class will receive all the fields from the join table. Details and code block for this solution as well as an alternative solution you can find here: How to create a geodatabase feature class ...


2

I am a novice in Python as well, but I have a script that will do what it sounds like you are trying to do - export all pages of an MXD with Data Driven Pages to one PDF. I run this through the toolbox in ArcCatalog or ArcMap. The MXD you are running it on does not have to be open. #Set Input Parameters mxd = arcpy.GetParameterAsText(0) PDFpath = ...


1

Juggling single quotes and double quotes can be a pain, but this should work: with arcpy.da.SearchCursor(Wells_Intersect_Layer, "COUNTY", '"COUNTY" = \'{}\''.format(cname)) as cursor: for row in cursor: Although you could probably also get around it by specifying the Where clause separately: # Count Wells in each County #for cname in countyList: ...


1

The problem may be in your where_clause. '"COUNTY "= ' + cname You have a space between the attribute name and quotation mark instead of quotation mark and equal sign, which I think will throw it off. Try instead: "COUNTY = '{}'".format(cname) "COUNTY = '" + cname + "'" # this is the same, but I find it harder to read! You need those quotation ...


3

The "Select Layer by Location" tool will select all wells in the existing layer that intersect any county. You're on the right track with the "intersect" operation: you'll find that you get the results you want by using the actual "Intersect" tool, which will create a new output feature class that contains attributes from both of the overlapping input ...


1

For panToExtent use the coordinates of your data frames coodinate system. As you said and Midavalo explained, the Point x = 30.317459, y = -97.694778 is measured in meters. So if you want to use geographic locations, change the coordinate sytem of your data frame or project the geographic coordinates into your UTM-Zone. For the last, it is discussed here: ...


1

Perhaps, instead of "hardcoding" into the system's environment (as below, can't comment there...), you could use a batch file instead: @echo off set PYSC_DIR=%~dp0 set ARC_VER="ArcGIS10.2" set ARC_DIR="E:\Esri\Desktop10.2\" set PYTHONPATH="%PYSC_DIR%\Lib\rpyc.zip";C:\Windows\system32\python27.zip;C:\Python27\%ARC_VER%\DLLs;C:\Python27\%ARC_VER%\lib; set ...


2

You're passing coordinates in meters to the panToExtent. It is not expecting Lat/Long, so when it pans it is correctly panning to 30m east and 97m south of your origin. This modification to your code will temporarily change your data frame's spatial reference, pan to your Lat/Lon, and change back. Note: I am unsure on the effect this may have on any ...


0

The asker provided this answer within their question, so it has been cut/paste to here: I figured out what the problem was. I was letting it run as a background program so it had no idea about the current workspace.


0

Another option will be to sort the point features spatially. Using the Sort function in your script, you can choose from which corner you want to start labeling (the 4 or 8 cardinal directions are supported). Make sure you select spatial rather than one of the fields in your attribute (I think you just need to specify the shape field)


1

I created a python script that does this for water meter routing. Just draw a line from the start to end of your points, set up your labeling and push go. If I remember correctly, the guts of it basically grabs one point at a time, gets the geometry and snaps it to the line. Then it finds the % along the line that that point is and adds it to a long list. ...


1

I would use a data access module da Update Cursor and the replace() method to accomplish this. The following is the preferred (new) method of using an Update Cursor. import arcpy shp = r'C:\path\to\shapefile.shp' with arcpy.da.UpdateCursor(shp, "your_field") as cursor: for row in cursor: row[0].replace("-", "") cursor.updateRow(row)


2

You could make a buffer along your line, then convert this buffer to polyline and finally use snap tool to snap points on this line. Python code should looks like this: import arcpy # Set workspace arcpy.env.workspace = r"path_to_your_workspace" # Set variables line_feature = "your_line_feautre.shp" point_feaure = "your_point_feature.shp" ...


0

Along a different line of thinking: import os ComputerName =os.getenv('COMPUTERNAME') txtFile.write("= Run By: "+str(ComputerName)),txtFile.write ('\n')


3

I suggest use parameter passing to the script while you call this script using task scheduler and grab this parameter using sys module- as below try: data = "= For ArcGIS 10.3.1: Date: "+str(timed)+ sys.argv[1]+'\n' #grab parameters passed except: data = "= For ArcGIS 10.3.1: Date: "+str(timed)+ "Arcgis tool used"+'\n' # else arcgis tool ...


1

You are receiving this error for the reason @crmackey provided in a comment: ListLayers is a function, not a class method. You have to pass in a MapDocument into ListLayers. His comment is based on you using ArcPy with the ArcGIS 10.x architecture. On the other hand you are reading documentation from ArcGIS Pro and appear to be assuming that the ...


1

May not be the approach you were looking for, but if you're just using a spatial intersection to get the match, then you could always take your new/updated feature class and run a spatial join against the original feature class. The output from that Spatial Join should have the ObjectID of the original feature class in it along with the attributes from the ...


1

I suppose you need something like this: cursor = arcpy.da.UpdateCursor("AVR_GEM","NAME"): for row in cursor: row[0] = str(row[0]).replace("ä","ae").replace("ö","oe").replace("ü","oe").replace(" ","").replace("(","") cursor.updateRow(row) Alternativly you may also directly change the row´s attribute: row.NAME = ...


3

Labels in ArcMap can have formatting codes within the expression, so something like: lblclass.expression = '"{}" + [OBJECTID] + "{}"'.format("<FNT size = '24'>","</FNT>") might work for you. This is adding font tags around your ObjectID into a label expression <FNT size = '24'> + OBJECTID + </FNT>


11

I assume you have installed comtypes successfully, according to the following SE Q/A: -How do I access ArcObjects from Python? import arcpy from snippets102 import * from comtypes.client import GetModule, CreateObject import comtypes.gen.esriFramework as esriFramework import comtypes.gen.esriArcMapUI as esriArcMapUI import comtypes.gen.esriCarto as ...


0

Two things.... 1) In arcpy.Exists(SQLDEVGIS + "\R_TRANSCO_PIPES") the string "\R..." needs to be prefaced with an 'r' to denote that it is a raw string. For example, should be: arcpy.Exists(SQLDEVGIS + r"\R_TRANSCO_PIPES") 2) In this environment the _SV denotes a spatial view. If you are trying to copy featureclasses then use ...


1

Are you sure you need to code this? It sounds like a great opportunity to use data-driven pages and dynamic text. More specifically, after you follow the instructions on ESRI's site to set up your data-driven map, you can simply insert into any text element: <dyn type="page" property="FieldOfInterest"/>, as seen here.


2

I think you just need to read the esri help file on ListLayers so you understand what it is actually being returned. This is the link. http://desktop.arcgis.com/en/desktop/latest/analyze/arcpy-mapping/listlayers.htm In particular, note how the layers are listed and how you can use the longName property of the layers to determine which layers belong to a ...


1

To test whether a layer or group layer returned by arcpy.mapping.ListLayers() is a layer or a group layer you can use the isGroupLayer property of a Layer object: Returns True if a layer is a group layer. For example, to progress your code you could try changing: for lyr in arcpy.mapping.ListLayers(mxd, "my_group_layer", df): group.append(lyr) ...


3

Calculate the X and Y coordinates into separate double fields. Use the Summary Statistics tool in the Analysis Toolbox->Statistics Toolset using the coordinate fields as Case fields (set up any other field as a summary field, but the summary does not really matter) to get a table with each unique point coordinate listed. Use the Make XY Event Layer tool in ...


0

I would tackle this problem in a completely different way. Cursors are great, but you really don't need one here. You basically want to select records according to a giant SQL Query, and delete those records. First, build up your query bit by bit, to make it more manageable. I would test the selections first individually and as a group: a = '"LAND1" = ...


3

!a! is not valid Python. Is this a typo? Calculate Field defaults to the VB parser, so you'll want to change that to Python. Something like the following should work: str.format() for reference. arcpy.CalculateField_management(fc, b, "!{}!".format(a), "PYTHON_9.3") To simplify things, you can combine all your for loops into one: for fc in ...



Top 50 recent answers are included