Stack Exchange Network

Stack Exchange network consists of 175 Q&A communities including Stack Overflow, the largest, most trusted online community for developers to learn, share their knowledge, and build their careers.

Visit Stack Exchange

New answers tagged

-1

The solution was to close down the project, add a save function, and then reopen the project to see that the files had been added. Simple as that.


0

I use the same code, with one exception. I use urllib2 Not sure if that is the cause of your error -- also I run this in ArcMap , does not work in ArcGIS Pro. Also make sure you do not have the database open in another program - as in - open in both ArcMap and Pro. import arcpy import urllib2 import json ...


4

You can iterate twice, first SearchCursor then UpdateCursor. Store values in a Collections.defaultdict(list) then use set to remove duplicates and join to create a string of the list. import arcpy from collections import defaultdict fc = r'C:\data.gdb\featureclass' fields = ['number','category','combined'] d = defaultdict(list) with arcpy.da.SearchCursor(...


1

16 bit signed integers can only store whole numbers between -32768 to 32767. Either keep in 32 bit floating point (and compress) or multiply by 10 before saving to 16 bit int to keep 1 decimal place, ie 483.41 becomes 4834.


0

Another way using collections.defaultdict(list), should work with any number of dates (not just 3 of the same): import arcpy from collections import defaultdict from random import shuffle fc = r'roadpoints' datefield = 'date' randfield = 'random' #Create a Dictionary with date as key and all oids of that date as a list of values d = defaultdict(list) with ...


0

You can do this in a single update cursor. You'll want to use dictionaries to keep track of each date's random pick and where in the count of each date you are. #update table tab = r"path\to\table" #date field dtFld = "Date" #random field ranFld = "Random" import arcpy import random #dictionary to store count of date countDi = {} #dictionary to store ...


0

autoLayer is a path for a geodatabase. It needs to be the path for a table. autoLayer = r"\\coacd.org...\autoLayers.gdb\OutputTable"


3

There are a few unnecessary steps in your code. MakeXYEventLayer should work from a CSV file, and possibly a .xlsx file*. You can also take advantage of having one single variable storing the path and then build upon that. If you want shapefile output, specify names with .shp. I used the GDB as output because I didn't see any extensions or another use for ...


1

I like using Python dictionaries. You can house your key and their respective XYs and use the dictionary to update your table. #point feature class pointFc = r"point\feature\class" #update table tab = r"update\table" import arcpy #create dictionary di = {} #iterate point feature class and store values with arcpy.da.SearchCursor (pointFc, ["No", "x", "x"]...


5

If you want to stick to python you can use a dictionary mydict= { 'Oshawa': '70', 'Toronto': '71a', 'Mississauga': '85', 'Kitchener': '77', 'Sudbury': '65' } if !CSDNAME! in mydict.keys(): !ZONE! = (mydict[!CSDNAME!]) else: #do something to flag Or you could create a table and districts and names and do a join. A left outer join (...


2

You can create a new feature class and use a data access insert cursor, projecting each Geometry with projectAs. Sample code; update with correct values for spatial reference, geometry type, etc.: mergeFcs = ["fc1", "fc2"] #merge feature classes outFc = "out_feature_class" #--- import arcpy outPath, outName = os.path.split (outFc) arcpy....


0

Check your quotation marks, also look at the ESRI SQL reference page Try this: SelectByAttribute = """CODE = '5020' OR CODE = '5601' OR CODE = '8002'""" arcpy.SelectLayerByAttribute_management("Bat_StudyArea", "NEW_Selection", SelectByAttribute)


2

Use IN in your SQL query, and don't include single quotes for numeric field values. CODE in (5020, 5601, 8002)


3

You can use selection and Python. This may be faster. Make sure your edited feature is selected. Then use the below code in the Python window. if arcpy.Describe ("layer").FIDSet: with arcpy.da.UpdateCursor ("layer", "update_field") as curs: for row in curs: row = ("U",) curs.updateRow (row) else: print "no selection" ...


0

I was also having this problem and the comment about the schema locks really helped. If you have an mxd with that feature class on it, it locks that feature class so it cannot be deleted. If you just exit the mxd that contains that feature class and run the same overwrite code, it seems to work.


0

Not sure if this still an issue for you but I was having the same problem and finally found the tag name "AccessInformation". I'm using 10.6.1 and the tag name does not have proper formatting(probably an ESRI BUG) but if you modify this in the sddraft manually and then stage a service it works. I just have to figure out how to create the tag in my script now....


0

This will work on a versioned database feature class: edit = arcpy.da.Editor(workspace) # Edit session is started without an undo/redo stack for versioned data # (for second argument, use False for unversioned data) edit.startEditing(False, True) # Create update cursor with arcpy.da.UpdateCursor("Your Parameters") as cursor: # Start an edit operation ...


7

All geoprocessing tools produce a Results object. You want the first output of your GetCount results object. The output will be a string, so you also must convert the string to an integer. if int (arcpy.GetCount_management(PolygonNeighbor_TableSelect) [0]) > 0:


3

The code needs to save the updated geodatabase path. Add aprx_new.save() right after aprx_new.defaultGeodatabase = geodatabase_path


0

Functioning Code with help from @Son-of-a-Beach: # This script prompts a user for an input directory containing MXDs, # and prompts for an output directory where PDFs are batch exported # This script exports both normal MXDs and MXDs with data driven pages enabled. import os, arcpy # user sets input and output directories input_dir = arcpy....


4

The error is in this line. # Process: Add Join arcpy.AddJoin_management(FiberCable, "THREEGISID", GDB_JOIN + FIBERCABLE_Project, "THREEGISID", "KEEP_COMMON") FiberCable, which is a variable with string "FiberCable", appears to be a feature class in your workspace. AddJoin requires a feature layer. FiberCableLyr = arcpy.MakeFeatureLayer_management (...


0

Esri: FAQ: How can I find all the places where domains are referenced in my geodatabase?. "Python functions that can list the properties of these structures in a geodatabase. Among the properties are the referenced domains. A sample script and file geodatabase are provided that demonstrate how Python functions might be used to list the domains and other ...


0

It looks like database locks, as Michael mentioned, was causing the issue. Releasing the locks allowed me to get past that error.


5

You are messing with the iterated variable, mxd within the for loop, but worse than that, you are assigning it an object within the loop which is of a completely different class to what the iteration assigns it. You should use two different variables instead. So instead of this: for mxd in mxdnames: input = os.path.join(ws, mxd) mxd = arcpy....


5

You need a colon after your line: if layer.supports(definitionQuery) should be: if layer.supports(definitionQuery): You should also consider modifying your query as was commented by @smiller. It will make your code easier to read.


2

To change an element's symbology you have to use the Apply Symbology from Layer tool. This means that you cannot directly specify the element's symbology from arcpy but you rather have to create a .lyr file and then apply it to the element using arcpy. The syntax of this tool in arcpy is the following: ApplySymbologyFromLayer_management(in_layer, ...


1

When you tell ArcGIS' Layer to KML tool to export a composite, it flattens all your data into a single image overlay. That means that any vector layers you had will now be combined with any rasters into a raster KML. If I remember correctly, ArcGIS exports the raster overlay at 2048x2048 pixels by default, which is quite small, and probably why it appears ...


0

I had forgotten to add the Header #!/usr/bin/python # -*- coding: utf-8 -*- before I added the script to the toolbox, I added the header after and it didn't affect the encoding until I deleted and then added the script to the toolbox again,


2

To add the values of a list into a Python list, use the extend method. e.g. extensionsofArcGIS = ['3D Analyst', 'Spatial Analyst', 'Geostatistical Analyst','Network Analyst', 'ArcScan'] extensionsofArcGIS.extend(['Terrain Editor', 'Test']) extensionsofArcGIS.sort() print extensionsofArcGIS Here are a few answers that go into detail on extend: https://...


2

If you want to use python then use sets: A set object is an unordered collection of distinct hashable objects. Common uses include membership testing, removing duplicates from a sequence, and computing mathematical operations such as intersection, union, difference, and symmetric difference contacted = ['123 STOWE ST', '123 ROSE DR', '124 ROSE DR',...


1

Thanks for the nudge, when creating the MWE I found I was reusing a field name by mistake. This was overwriting the results to appear like it did not do anything. The code now does what I tell it. Not sure yet if thats what I want. This code now works: # -*- coding: utf-8 -*- '''---------------------------------------------------------------------...


3

It depends on what you mean by "view" and "as a database". To simply extract the data from a table into a data structure in Python using Arcpy, use arcpy.da.SearchCursor(). See: https://pro.arcgis.com/en/pro-app/arcpy/data-access/searchcursor-class.htm If this answer is too vague, that's probably because you're question is a little on the vague side, and ...


3

You have not specified what your hwsd_csv value is. However, you need to use the name of the data source, not the name of the table view when removing a join. So, based on the values in the error message, perhaps the following might work: arcpy.RemoveJoin_management("hwsd_lyr", "HWSD_CLS_DATA") or possibly: arcpy.RemoveJoin_management("hwsd_lyr", "...


2

You don't need to use a cursor for this. You can create a layer using a 'where' clause so that it only includes the features that match your criteria. Then copy that layer to your new shapefile. If fact, you can even skip creating a layer and you can use FeatureClassToFeatureClass_conversion() to do it all in one step as that function includes an optional '...


2

To specify the output you'll want to use either arcpy.SetParameter() or arcpy.SetParameterAsText() depending if you want to output an object or return text. I am guessing you want to use the filename of your merged feature class so I would add the following line to the end of your script: arcpy.SetParameterAsText(1, 'merge_result') Also, check this answer:...


0

Create a new cursor for each interval. for i in range(-100,100,1): with arcpy.da.UpdateCursor("WorldPoint",("SHAPE@XY",),'"'+'FID"'+' = 0') as cursor: for row in cursor: row[0] = (float(-74.668),float(i)) cursor.updateRow(row) arcpy.RefreshActiveView() time.sleep(1) You probably want to apply your SQL query ...


0

Ok, so I got it working arcpy.SelectLayerByAttribute_management("buffcut", "SWITCH_SELECTION") I needed to wrap buffcut with "". I thought setting it earlier on was the correct method but apparently not!


4

This is a limitation of Shapefiles which cannot store both date and time in the same field. The ESRI documentation at https://pro.arcgis.com/en/pro-app/help/data/tables/date-fields.htm says: When calculating date fields, the field calculator uses Python datetime functions. Some of the functions support datetime yyyy-mm-dd hh:mm:ss AM or PM. However, for ...


2

I would use data access search and insert cursors after creating a new feature class. This will most likely be slower than the Buffer tool but it may be more successful, or you may be able to find your problematic geometry with try/except statements. Basic script: import arcpy import os i = 'PCPP_sites' o = 'C:\buffer_test' outPath, outName = os.path.split ...


1

You'll want to make use of an extent object. Get the extent of your layer. Next set your data frame extent to the layer's extent. add_substation = arcpy.mapping.Layer('mcarthur.lyr') df = arcpy.mapping.ListDataFrames(mxd, 'Data_Frame')[0] #set data frame extent to layer's extent df.extent = add_substation.getExtent ()


2

This line is essentially overwriting the entry in the ftcs dictionary within the loop: ftcs[row[0]] = [row[1], segment_dates.get(row[1])] Hence you ending up with just one date entry. I think you need to explore the dictionary method has_key() to check for the existing entry then return the value (your list) with ftcs[row[0]] ,lets call it mylist, update ...


0

You have to check if your csv files do not contain fields with an unauthorized length. Also, you have to make sure that your both elements (OS. path. splitext (OS. path. basename (csv)) [0] +'_lyr' and OS. path. splitext (OS. path. basename (csv)) [0] +'_csv') have the same field type and the same length concerning your field 'GEOID'.


3

The SpatialReference object which can be accessed using Describe has the name property: import arcpy arcpy.env.workspace = r'X:\somefolderwithrasters' rasters = arcpy.ListRasters() for r in rasters: spatref = arcpy.Describe(r).spatialReference print 'Raster: {0} has spatial reference: {1}'.format(r, spatref.name) Example output: Raster: s1milj....


-1

The Split tool in ArcGIS does exactly this.


3

One of the interesting quirks of many SQL client APIs is the lack of a "table exists" function. Many implementations of an "exists" are really a low-level "describe", which returns a "does not exist" error if the table doesn't exist, and populates metadata if it does. The side effect of this is that an "exists" test is often quite slow, because if it ...


0

Use this on a sorted copy of your polygons: import arcpy ## works on sorted table !!! g=arcpy.Geometry() geomList=arcpy.CopyFeatures_management("POLYGONS",g) N=0 with arcpy.da.UpdateCursor("POLYGONS","Shape@") as cursor: for row in cursor: N+=1 if N==len(geomList):break origPgon=row[0] newPgon=origPgon.difference(geomList[...


0

A solution that works for me it's to divide script into two: - first script iterate on an item list, pass an "id_item" to the second, and erase temporal files - second script do geoprocess for each item. Note: in sample code there is a comented sample geoprocess, it's only for take an idea of what could be. First script (01_call_process.py): import ...


0

I don't believe you can access those properties as the symbologyType property on a raster layer with a stretched symbology returns the unsupported "other".


4

It looks like you’re setting the ‘cumulative’ field to the area of that record only, not the running total. Try replacing: row[1] = AreaValue with: row[1] = running


1

I recently needed to do convert a REST service to a Feature Class as well. Here is a MWE of my approach (using requests rather than urllib). import json import arcpy import requests # arcpy env settings arcpy.env.workspace = 'path_to_your_gdb' # get data from rest service params = {'where': '1=1', 'outFields': '*', 'f': 'pjson', 'returnGeometry': True} r ...


Top 50 recent answers are included