Useful Arcpy Commands and Code Snippets: Nick Eubank May 16, 2014
Useful Arcpy Commands and Code Snippets: Nick Eubank May 16, 2014
Nick Eubank
Individual Functions
Data Manipulation
1
Selections
Selections can be applied to either one of the two types of layers in ArcPy (see Tutorial, Section
8 for a discussion of layers). Selections can only be applied to layers, not feature classes!
• Create a Feature Layer from featureclass: MakeFeatureLayer management()
Cartography
You can also use ArcPy to manipulate Map Documents (ending in .mxd). This is useful for
cartography, and has it’s own set of tools.
When working with cartography, one often also works with selections. However, this is an area
I don’t know well, so this is admittedly thin!
• Create Map Document Variable: mapping.MapDocument(“file.mxd”)
e.g. mxd = arcpy.mapping.MapDocument(“file.mxd”)
• Set the extent of the Map Document (i.e. zoom) to extent of selected elements of a layer
(called myLayer):
lyrExtent=myLayer.getSelectedExtent()
df.extent=lyrExtent
try:
arcpy.Delete_management(Output,HomeFolder)
print "Deleted Old Database"
except:
# Output.gdb did not exist, pass
print "Did not delete"
pass
arcpy.CreateFileGDB_management(HomeFolder, Output, "CURRENT")
print "Created New Database"
2
Cartography: Zoom to different constituencies and print PDFs of each con-
stituency
mxd = arcpy.mapping.MapDocument("pc_maps_forexport.mxd")
mxd.author="Nick Eubank"
#mxd.save()
# Now I want to draw out the first item in the current data frame --
so call for list then subscript for item "0" Of course I only have one
data frame, but this precludes the possibility I’ll get back a list
instead of a single item.
df=arcpy.mapping.ListDataFrames(mxd, "Layers")[0]
# Call list of layers. If you add a [0] to the end, you get a single
object. I just pull out the objects in the next few lines. My first
layer (lyrList[0]) is the layer of PC locations. The second (lyrList[1])
is a constituency map.
lyrList=arcpy.mapping.ListLayers(mxd)
print lyrList
pcsLayer=lyrList[0]
constsLayer=lyrList[1]