Hot answers tagged

13

If you have Arc 10.1 or above, I'd use an arcpy.da cursor. Also specify just the field(s) you want. myLayer = 'YourLayer' myField = 'YourField' myList = [row[0] for row in arcpy.da.SearchCursor(myLayer, myField)]


11

The way I would set your task up would be to create a custom script which provides greater flexibility than the modeler but can still provide a similar interface to its users. You can create one from: Processing Toolbox > Scripts > Tools > Create new script Then copy/paste the script below and save it into C:/Users/You/.qgis2/processing/scripts. The ...


10

This is one way to go about it: This python snippet will loop over a directory, get all of the filenames that end with a .jpg extension and the create a new text file with the new .fsv extension - this file will contain whatever text you choose to write to it. import glob import os os.chdir("\dir") #the directory containing your .jpegs for file in ...


10

Just to add on to the other answers, you can avoid having to explicitly call the file object's close() method if you use a with statement (which automatically calls close() even if an exception is raised): with open(filename, 'w') as f: f.write("open=" + jpg + " set to 100") Also don't forget to write a line-ending if that is the intention...


9

The ModelBuilder functions (like arcpy.IterateFiles_mb) only work within ModelBuilder, and don't do as desired within a Python script. But, for loops do just as well (if not better). In this case, you want to loop through all the .asc files in a workspace. Define the workspace (you got that far): import arcpy from arcpy import env env.workspace = r"D:\...


9

In theory (because I don't know arcpy), simply use the standard function enumerate (GeoNet: Enumeration of a cursor) for i, row in enumerate(cur): row[0] = i cur.updateRow(row)


8

The easiest option would be to reference the OID in the attributes using the OID@ token in a SearchCursor. import arcpy shp = r'X:\path\to\your\shapefile.shp' with arcpy.da.SearchCursor(shp, ["OID@", "some_field"]) as cursor: for row in cursor: print row Alternatively, building on gene's answer, Python's built-in enumerate function can make a ...


8

Try using an UpdateCursor: import arcpy stands = r'D:\mountaine\database.mdb\testPoly' arcpy.MakeFeatureLayer_management(stands,'pormap') with arcpy.da.UpdateCursor("pormap", [ 'TEXTSTR', 'NUMBR', 'RESULTS']) as searchIng: for x in searchIng: if x[0] == 'BK': x[2] = x[1]*1 elif x[0] == 'SM': x[2] = x[1]*2 ...


7

There's a couple of things to notice: In your algorithm, you are using rstr (the path of the rasters) as the input instead of the actual rasters which you have defined as lyr. This probably depends on the Processing plugin version but in v2.10.2, the algorithm gdalogr:cliprasterbymasklayer requires 7 parameters (you mentioned 6). You can check this by using ...


7

Linux (ubuntu as you call it) uses a shell (probably bash in this case) which has a different syntax to windows so you want something like: for i in se70*.tif do gdalinfo $i done


7

Never, never, never use embedded cursor loops. Never! It is bad for performance, memory, data safety, etc. It is very, very bad. See my blog on Turbo Charging Data Manipulation with Python Cursors and Dictionaries. Load the look up table into a dictionary with a data access search cursor, then update the other table with an update cursor by matching it ...


7

You have misunderstood how the updateRow method works. It is a method of the cursor as a whole and takes a row object as its argument: fromUpdateCursor_4Depth.updateRow(updateFromRow) You have to assign all of your update variables to the row object to write them to that row. I am not sure how your update fields match up with the variables, but they ...


7

SelectLayerByLocation requires a Layer to select features, you can't select features directly on a feature class, which is what your script is trying to do. The reason it worked in ArcMap is because in ArcMap you were referencing the map layers rather than feature classes. Add a MakeFeatureLayer and set your SelectLayerByLocation to select that. for grid ...


6

Because you're asking in GIS, I'm including arcpy in my answer. ;) import arcpy from arcpy import env env.workspace = r'C:\your\path\here' jpgList = arcpy.ListFiles("*.jpg") for jpg in jpgList: jpgnum = jpg[:-4] filename = jpgnum + '.fsv' f = open(filename, 'w') f.write("open=" + jpg + " set to 100") f.close() And that's it!


6

You need to use arcpy.ListFeatureClasses(), not ListDatasets(). This code is directly from the online help. Just replace "CopyFeatures" with "Rename". import arcpy from arcpy import env import os # Set the workspace for the ListFeatureClass function # env.workspace = "c:/base" # Use the ListFeatureClasses function to return a list of # all shapefiles. ...


6

The problem is definitely the old-type cursor. It often makes some problems with nested loops. I recommend you to use da.SearchCursor. The code should look like this: with arcpy.da.SearchCursor(shapePocz, ["numer"]) as searchCursOuter: for pktPocz in searchCursOuter: with arcpy.da.SearchCursor(shapeKonc, ["numer"]) as searchCursInner: ...


6

Here, just reorganize your try/except block and put it inside the for loop: for workspace in workspaces: try: arcpy.Compress_management(workspace) except: arcpy.GetMessages()


5

First of all, I agree with @SS_Rebelious. Your "zipcoords" object seems to represent a common data extent so, rather than creating a list object, why not just create a stack object of your rasters and extract everything at once? If common extents are a problem in the rasters, you can use the "quick=TRUE" argument in stack() to override the extent error. ...


5

To find the name of the dataset as stored in the database use IDataset.BrowseName. IDataset.Name will give you the layer name as it is named in ArcMap. You should also test that the layer can be cast to IDataset: If TypeOf currentLayer Is IDataset Then... Things like group layers don't implement IDataset, and will cause an error.


5

There's no need for a for (or any other kind of) loop since such stuff is entirely included in the raster package. If you want to calculate the NDVI, then basically all you need is ## required package library(raster) ## calculate ndvi from red (band 1) and near-infrared (band 2) channel ndvi <- overlay(StackBand1, StackBand2, fun = function(x, y) { (y-...


5

This is because you create a selection on your gridDivision layer. The cursor then only iterates through selected features. Clear your selection after your cursor. # Go through all lines feature classes for lineFC in linesList: print "THIS IS THE LINE FILE: "+lineFC with arcpy.da.SearchCursor(gridDivision, ["OID@"]) as cursor: for oid in ...


5

You said that the datatype of the DB column is a number, but in your if and elif statements you compare that number to a string (e.g. 4 == '4') which will return False. Maybe you get the desired result when you remove the single quotes around the numbers, for example: row[0] == 4: instead of row[0] == '4':.


5

You're tripping over your own feet here.. All cursors need to be removed or they will lock the data; until you free the cursor you could still go back to it at any stage. In your code you're using a mixture of old and new style cursors, I wouldn't, try to stick to one or the other. They both work but I would use arcpy.da cursors exclusively. Older style ...


5

This code should do the work you need to get done. Make sure the table is sorted as you expect. There is a GP tool Sort that can do that for you. import arcpy fc = r'C:\ArcGIS\Default.gdb\wells' with arcpy.da.UpdateCursor(fc,['MD','FM_Name']) as upd_cur: for row in upd_cur: #start iterating rows in the table if row[1] == 'TOP': #if the FM_NAME ...


5

Use arcpy.Exists() if arcpy.Exists(r"MyFeatureClass"): print "Feature Class Exists" else: print "Feature Class Doesn't Exist" Additionally, look into arcpy.CreateUniqueName() to generate a new output name if the one you want to use already exists uniqueName = arcpy.CreateUniqueName(r"MyFeatureClass") arcpy.Buffer_analysis(r"InputFC", uniqueName, "...


5

I think you have a misunderstanding of cursors and calculate field, these methods are mutually exclusive (if you use one don't use the other). The answer by Richard Morgan is correct, however there is another way, by inserting a code block into calculate field (read more about code blocks); If you specifically need to use Calculate Field and not an update ...


5

I belive the QgsFeatureIterator is closed after returning all features. Example: >>layer = iface.activeLayer() >>feats = layer.getFeatures() >>[f['GRID_ID'] for f in feats] ['AP7', 'AP8', 'AP9', 'AP3', 'AP4', 'AP5', 'AP6', 'AP1', 'AP2'] >>[f['GRID_ID'] for f in feats] [] #No more features are return after used once >>feats =...


4

Why not something like this: folders = ["s41120", "s42120", "s42121", "s43120", "s43121", "s44120", "s44121"] path = r'z:\z11_10m' for folder in folders: working = os.path.join(path, folder) outworking = os.path.join(path, "project", folder) arcpy.workspace = working for raster in arcpy.ListRasters("*"): outname = os....


4

The paths with a single backslash are no valid paths. Use: one forward slash: "c:/test/test.shp" Two backslash: "c:\\test\\test.shp" letter r before a string containing a backslash: r"c:\test\test.shp"


4

I'm a little confused by your code. I think you can just use a single cursor to add the geometry and the name in one go--there's no need to use an insert cursor and an update cursor. Also, you should create your cursor outside of your for loop. cursor = arcpy.InsertCursor(trackPolyLine) for key in dictionary: feature = cursor.newRow() polyLine = ...


Only top voted, non community-wiki answers of a minimum length are eligible